[英]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.