我有一个结果集如下,我有来自不同供应商的相同产品。我想确定所有供应商的价格不一样的集合
PRODUCT_ID STORE_ID PRICE
60 1 10.00
60 2 10.00
60 3 10.00
65 1 9.00
65 2 8.50
65 3 9.00
66 1 21.00
66 2 21.00
66 3 21.00
67 1 16.00
67 2 15.00
67 3 19.00
我的SQL查询应该返回两个并非所有供应商都有相同价格的集合
65 1 9.00
65 2 8.50
65 3 9.00
67 1 16.00
67 2 15.00
67 3 19.00
答案 0 :(得分:2)
更新:一种方法
SELECT *
FROM table1 t JOIN
(
SELECT product_id
FROM table1
GROUP BY product_id
HAVING COUNT(DISTINCT price) > 1
) q ON t.product_id = q.product_id
输出:
+------------+----------+-------+------------+ | PRODUCT_ID | STORE_ID | PRICE | product_id | +------------+----------+-------+------------+ | 65 | 1 | 9.00 | 65 | | 65 | 2 | 8.50 | 65 | | 65 | 3 | 9.00 | 65 | | 67 | 1 | 16.00 | 67 | | 67 | 2 | 15.00 | 67 | | 67 | 3 | 19.00 | 67 | +------------+----------+-------+------------+
答案 1 :(得分:0)
您可以尝试以下
select * from product_table
where product_id in
(
select product_id
from product_table
group by product_id
having max(price) = avg(price)
)
答案 2 :(得分:0)
我的查询与 peterm 的查询非常相似,但我使用了IN()子句。在我看来,看起来更简单。对于性能问题,使用JOIN或IN()没有区别:)
SELECT *
FROM PRODUCTS_VENDORS
WHERE PRODUCT_ID IN ( SELECT PRODUCT_ID
FROM PRODUCTS_VENDORS
GROUP BY PRODUCT_ID
HAVING COUNT (DISTINCT PRICE) > 1);