我有一张这样的表:
+------+------+
|Product|Warehouse|
+-------+------+
|1 |A |
+-------+------+
|2 |A |
+-------+------+
|3 |A |
+-------+------+
|1 |B |
+-------+------+
|2 |B |
+-------+------+
我想选择使用不同仓库多次出现的产品。
输出应该是这样的:
+------+------+
|Product|Warehouse|
+-------+------+
|1 |A |
+-------+------+
|1 |B |
+-------+------+
|2 |A |
+-------+------+
|2 |B |
+-------+------+
这让我分道扬:
SELECT *
FROM YourTable
WHERE Warehouse IN (
SELECT Warehouse
FROM YourTable
GROUP BY Warehouse
HAVING COUNT(*) > 1
)
但我还想为Warehouse指定一组值。所以我想要做的是看到存在于多个仓库中的产品,但我希望能够指定我想要看到的仓库。
我将使用Oracle SQL Developer。
答案 0 :(得分:0)
你可以试试这个:
http://rextester.com/LQZJ62189
drop table if exists your_table;
create table your_table ( product int, warehouse varchar(1));
insert into your_table values
(1, 'A'),
(2, 'A'),
(3, 'A'),
(1, 'B'),
(2, 'B');
select * from your_table
where product in (
SELECT product
FROM your_table
GROUP BY product
HAVING count(warehouse) > 1)
order by product;
答案 1 :(得分:0)
如果要将子查询移动到JOIN子句,可以执行以下操作:
SELECT *
FROM your_table T1
INNER JOIN (SELECT Warehouse
FROM your_table2
GROUP BY Warehouse
HAVING COUNT(Product) > 1) T2
ON T1.Warehouse = T2.Warehouse;
答案 2 :(得分:0)
id2
我自己加入了同样的产品和不同的wharhouse,结果将是所有产品存在于多个wharhouse中。如果此表中没有产品和wharhouse的副本,则此代码是正确的。
答案 3 :(得分:0)
您自己的尝试非常接近,但它显示的仓库中有多个产品,而不是相反。
因此:
SELECT *
FROM YourTable
WHERE Product IN (
SELECT Product
FROM YourTable
GROUP BY Product
HAVING COUNT(*) > 1
)