SQL仅列出带子查询的唯一值

时间:2013-10-15 13:47:06

标签: mysql 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;

任何帮助都将受到高度赞赏 - 谢谢!

4 个答案:

答案 0 :(得分: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)

如果您需要使用子查询来解决此问题,您希望找到NOT EXISTS其他产品等于=)discountPercent的产品,而不是不同的<>)。仅当表中的所有discountPercents具有相同的值(不存在具有不同折扣的任何其他产品)时,在<>子句中使用NOT EXISTS才会返回结果 - &gt;所有折扣均为相同)

并考虑到您需要添加一个条件以确保子查询没有找到执行它的同一行的匹配(即p1p2不同的行})

例如,如果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;

答案 2 :(得分: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

答案 3 :(得分:0)

在mysql中尝试此查询

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