[英]alternative to sum in sql where clause
I have table1 which represents an order summary. 我有代表订单摘要的table1。 In table1 has a one to many relationship with table2, which represents the different items that are part of the order.
表1中的表与表2有一对多关系,表2代表订单中不同的项目。 table1 has a field for quantity, which should represent the total number of individual items that are part of the order.
table1有一个数量字段,该字段应表示订单中各个项目的总数。 In table2 the quantity field that represents the number of individual items for that item type.
在表2中,数量字段表示该物料类型的单个物料的数量。
I want to see what is not conforming to this rule (I have reason to believe the rule was broken) 我想看看什么不符合此规则(我有理由相信该规则已被打破)
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)
You can use a having
clause to apply a condition to a group: 您可以使用
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.