2013-10-15 46 views
2

讓我開始說是這是一個家庭作業問題。SQL僅列出子查詢中的唯一值

看起來很簡單,但我無法使它工作。我只是開始子查詢,我猜這就是我的老師在這裏想要的。

這裏的問題

5. Write a SELECT statement that returns the name and discount percent 
    of each product that has a unique discount percent. In other words, 
    don’t include products that have the same discount percent as another 
    product. 
    -Sort the results by the ProductName column. 

這裏就是我試圖

SELECT DISTINCT p1.ProductName, p1.DiscountPercent 
FROM Products AS p1 
WHERE NOT EXISTS 
    (SELECT p2.ProductName, p2.DiscountPercent 
    FROM Products AS p2 
    WHERE p1.DiscountPercent <> p2.DiscountPercent) 
ORDER BY ProductName; 

任何幫助,將不勝感激 - 謝謝!

回答

1

試試這個,它和你的很相似,但是not in你可以保證這個折扣在其他產品中不存在。

SELECT p1.ProductName, p1.DiscountPercent 
FROM Products AS p1 
WHERE p1.DiscountPercent NOT IN 
    (SELECT p2.DiscountPercent 
    FROM Products AS p2 
    WHERE p1.ProductName <> p2.ProductName) 
ORDER BY ProductName 
+0

我看到現在如何,非常感謝! – Taylor

2

當使用COUNT()唯一性檢查變得非常簡單,您可以使用它在一個HAVING條款或選擇它徹底。

SELECT a.ProductName, a.DiscountPercent 
FROM Products a 
JOIN (SELECT DiscountPercent, COUNT(DiscountPercent) AS CT 
     FROM Products 
     GROUP BY DiscountPercent 
    )b 
ON a.DiscountPercent = b.DiscountPercent 
WHERE b.CT = 1 

或者:

SELECT a.ProductName, a.DiscountPercent 
FROM Products a 
JOIN (SELECT DiscountPercent 
     FROM Products 
     GROUP BY DiscountPercent 
     HAVING COUNT(DiscountPercent) = 1 
    )b 
ON a.DiscountPercent = b.DiscountPercent 
+1

+1來解釋它是如何工作以及爲什麼原始查詢沒有這將是有益的。 – Tarik

+0

謝謝你們每一個山羊CO!工作很好 – Taylor

1

如果需要使用子查詢解決這個問題,你想找到產品,其NOT EXISTS其他產品與等於=)discountPercent,不不同<>)。在NOT EXISTS子句中使用<>只會在表中所有discountPercents具有相同的值時才返回結果(不存在任何其他具有不同折扣的產品 - >所有折扣都相同)

並考慮帳戶,您需要添加一個條件,以確保子查詢執行它沒有找到一個匹配同一行(即p1是不一樣的行作爲p2

舉例來說,如果productName足以確定一個product

SELECT DISTINCT p1.ProductName, p1.DiscountPercent 
FROM Products AS p1 
WHERE NOT EXISTS 
    (SELECT p2.ProductName, p2.DiscountPercent 
    FROM Products AS p2 
    WHERE p1.DiscountPercent = p2.DiscountPercent 
      AND p1.ProductName <> p2.ProductName) 
ORDER BY ProductName; 
+0

也很好的答案感謝您的幫助 – Taylor

+0

很高興幫助,特別是如果它幫助你瞭解原因:-) –

0

嘗試此查詢在MySQL

select ProductName, DiscountPercent 
from product 
where DiscountPercent in (select DiscountPercent from product 
           group by DiscountPercent 
           having count(DiscountPercent)=1)