繁体   English   中英

替代SQL where子句中的sum

[英]alternative to sum in sql where clause

我有代表订单摘要的table1。 表1中的表与表2有一对多关系,表2代表订单中不同的项目。 table1有一个数量字段,该字段应表示订单中各个项目的总数。 在表2中,数量字段表示该物料类型的单个物料的数量。

我想看看什么不符合此规则(我有理由相信该规则已被打破)

SELECT table1.id, table1.quantity, table2.orderid, table2.itemqty
FROM table1
INNER JOIN table2 on tabel1.id = table2.orderid
WHERE table1.quantity != SUM(table2.itemqty)

您可以使用having子句将条件应用于组:

select  t1.id
,       t1.customer
,       t1.quantity 
,       sum(t2.itemqty)
from    table1 t1
join    table2 t2
on      t1.id = t2.orderid
group by
        t1.id
,       t1.customer
,       t1.quantity 
having  t1.quantity <> sum(t2.itemqty)
SELECT     table1.id, 
           table1.quantity, 
           table2.orderid, 
           table2.itemqty
FROM       table1
INNER JOIN ( 
               SELECT orderid,
                      SUM(itemqty) as itemqty 
               FROM   table2 
               GROUP BY orderid
           ) table2 
           on tabel1.id = table2.orderid
WHERE      table1.quantity <> table2.itemqty

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM