我有下表,我想获得只有非活动状态的产品。某些产品具有活动和非活动状态。但是,我不希望他们进入最终名单。我只需要只有非活动状态的产品。
+-----------+----------+
| ProductID | Status |
+-----------+----------+
| 152141 | Active |
| 152141 | Inactive |
| 157874 | Active |
| 152478 | Inactive |
| 152478 | Inactive |
| 157875 | Active |
| 157875 | Active |
| 157875 | Inactive |
+-----------+----------+
并且期望的结果在这里。
+-----------+----------+
| ProductID | Status |
+-----------+----------+
| 152478 | Inactive |
+-----------+----------+
提前谢谢。
答案 0 :(得分:1)
您可以在productID Active
中使用notselect distinct ProductID, Status
from my_table
where ProductID not in (
select productID from my_table where status = 'Active'
)
答案 1 :(得分:0)
执行GROUP BY
,确保只有非活动行。
select ProductID, Status
from tablename
group by ProductID
having min(Status) = 'Inactive'
答案 2 :(得分:0)
尝试类似(对于Oracle):
SELECT ProductId
FROM TableName
MINUS
SELECT ProductId
FROM TableName
Where Status = 'Inactive'
或者,使用EXCEPT
(对于SQL Server):
SELECT ProductId
FROM TableName
EXCEPT
SELECT ProductId
FROM TableName
Where Status = 'Inactive'
感谢@jarlh的评论。
答案 3 :(得分:0)
http://sqlfiddle.com/#!4/74f9a/3/0
CREATE TABLE Table1
(ProductID int, Status varchar2(8))
;
INSERT ALL
INTO Table1 (ProductID, Status)
VALUES (152141, 'Active')
INTO Table1 (ProductID, Status)
VALUES (152141, 'Inactive')
INTO Table1 (ProductID, Status)
VALUES (157874, 'Active')
INTO Table1 (ProductID, Status)
VALUES (152478, 'Inactive')
INTO Table1 (ProductID, Status)
VALUES (152478, 'Inactive')
INTO Table1 (ProductID, Status)
VALUES (157875, 'Active')
INTO Table1 (ProductID, Status)
VALUES (157875, 'Active')
INTO Table1 (ProductID, Status)
VALUES (157875, 'Inactive')
SELECT * FROM dual
;
查询 -
SELECT distinct t1.ProductID, t1.Status
from Table1 t1
where t1.Status = 'Inactive'
and not exists (
select 1 from Table1 t2
where t2.ProductID = t1.Productid
and t2.Status = 'Active');
输出 -
PRODUCTID STATUS
152478 Inactive
答案 4 :(得分:0)
SELECT DISTINCT t1.ProductID, t1.Status
FROM tblProduct t1
WHERE NOT EXISTS(SELECT 1
FROM tblProduct t2
WHERE t2.Status = 'Active'
AND t2.ProductID = t1.ProductID)
AND t1.Status = 'Inactive'
GROUP BY t1.ProductID, t1.Status;
答案 5 :(得分:0)
我会将NOT EXISTS
与您不想要的过滤(Status = 'Active'
)一起使用:
select distinct t.*
from table t1
where not exists (select 1
from table t2
where t2.ProductID = t1.ProductID and
t2.Status = 'Active');
您也可以使用GROUP BY
子句
select ProductID, max(Status) as Status
from table t
group by ProductID
having min(Status) = max(Status) and min(Status) = 'Inactive';