将行的值与另一个表中的多行进行比较

时间:2014-10-27 09:51:12

标签: sql sql-server tsql

让我们想象一下,我有两张订单表,我想与彼此进行比较。

orders {
   id int, 
   price money
}

ordereditems {
   orderid int, 
   itemid int,
   price money
}

其中 orders.id = ordereditems.orderid

当然,这是一个糟糕的设计,因为两张桌子都不需要价格。但是,如何设计查询以查明订单中哪些行的价格与订购项目中的价格列总和不匹配?

4 个答案:

答案 0 :(得分:1)

如果我理解正确:

SELECT * FROM orders o
LEFT JOIN OrderedItems ei
ON o.Price = ei.Price WHERE ei.Price is NULL

答案 1 :(得分:0)

SELECT a.id,
       a.price,
       b.price,
       CASE
         WHEN a.price = b.price THEN 'PRICE MATCHED'
         ELSE 'PRICE NOT MATCHED'
       END AS RESULT
FROM   orders a
       INNER JOIN ordereditems b
               ON a.id = b.orderid
                  AND a.price IS NOT NULL 

- 订单的价格与orderitems中的pricecolumn的总和不匹配

SELECT a.id,
       a.price,
       b.total_price,
       CASE
         WHEN a.price = b.total_price THEN 'PRICE MATCHED'
         ELSE 'PRICE NOT MATCHED'
       END AS RESULT
FROM   orders a
       INNER JOIN (SELECT orderid,
                          Sum(price) AS total_price
                   FROM   ordereditems
                   GROUP  BY orderid) b
               ON a.id = b.orderid
                  AND a.price IS NOT NULL 

答案 2 :(得分:0)

对两列中的值求和的最简单方法是优先选择现有的值:

SELECT SUM(COALESCE(o.price, oi.price)) as price -- reorder columns for prefer
FROM orders o INNER JOIN -- if you are missing some rows use FULL JOIN
ordereditems oi ON oi.id = o.id

答案 3 :(得分:0)

您还可以使用以下查询来获取价格不匹配的订单ID

SELECT o.id,MAX(o.price) AS price
FROM orders o
INNER JOIN ordereditems oi
ON o.id=oi.orderid
GROUP BY o.id
HAVING SUM(oi.price)<>MAX(o.price)