2014-10-27 69 views
0

讓我們假設我有兩張我想與其他人互相比較的訂單表。比較另一個表中多行的行的值

orders { 
    id int, 
    price money 
} 

ordereditems { 
    orderid int, 
    itemid int, 
    price money 
} 

其中orders.id = ordereditems.orderid

當然,這是一個不好的設計,因爲這兩個表並不需要一個價格。但是,如何設計查詢以查明訂單中的哪些行具有價格,這與訂購商品中價格列的總和不相符?

+0

嘗試使用左連接上orders.id = ordereditems.orderid,做的比較或什麼都計算u需要 – 2014-10-27 09:56:57

回答

1

如果我理解正確的:

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

你沒有,謝謝:) – Dave 2014-10-27 10:06:13

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 

--orders有一個價格,這與pricecolumn的ordereditems總和不匹配

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 
+0

這是行之有效的,只要每個訂單隻有一個訂單項。如果一個訂單包含兩個項目,則不起作用:( – Dave 2014-10-27 10:16:33

+0

計算OrderedItems表中所有項目的價格,USE GROUPBY – knkarthick24 2014-10-27 10:20:13

+0

檢查編輯後的代碼。 – knkarthick24 2014-10-27 10:25:47

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 
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) 
相關問題