我正在使用Oracle Server:
我有下表。我试图让“客户”的“产品”状态为“无效”。但是,如果同一客户的任何产品状态为有效。我不会列出那些。
+----------------+---------+----------+
| Client | Product | Status |
+----------------+---------+----------+
| John & Co. | 12548 | Active |
| John & Co. | 58451 | Inactive |
| Vector Inc. | 12243 | Inactive |
| Vector Inc. | 84425 | Inactive |
| Ambro Info. | 11145 | Inactive |
| Infy Tech inc. | 12473 | Active |
| Infy Tech inc. | 84847 | Active |
+----------------+---------+----------+
预期结果:
+-------------+
| Client |
+-------------+
| Vector Inc. |
| Ambro Info. |
+-------------+
我们可以使用Oracle Query来实现这一目标吗。
答案 0 :(得分:0)
不存在
select t1.Client from table_name t1 where
not exists ( select 1 from table_name t2 where t2.Client=t1.Client and t2.status='Active')
with cte as
(
select 'john' as client,12548 as product, 'Active' as status
union all
select 'john' as client,58451 as product, 'Inactive' as status
union all
select 'Vector Inc', 12243 , 'Inactive'
)select t1.client from cte t1 where
not exists ( select 1 from cte t2 where t2.client=t1.client and t2.status='Active'
)
client
Vector Inc
Ambro Info
答案 1 :(得分:0)
create table #temp (cst varchar(50),prodid int,tag varchar(40))
insert intO #TEMP
VALUES('John & Co.',12548,'Active'),
('John & Co.',58451,'Inactive'),
('Vector Inc',12243,'Inactive'),
('Vector Inc',84425,'Inactive'),
('Ambro Info.',11145,'Inactive'),
('Infy Tech inc',12473,'Active'),
('Infy Tech inc',84847,'Active')
SELECT DISTINCT T.CST FROM #temp T
WHERE T.CST NOT IN(SELECT Z.CST FROM #temp Z WHERE TAG='ACTIVE')
答案 2 :(得分:0)
以相反的方式思考,您需要实现所有不在活动列表中的客户端,因此我们可以进行一个简单的查询:(我在这里使用#temp
表来表示您的表)
SELECT DISTINCT client
FROM #temp
WHERE status = 'Inactive' -- just incase there are more status rather than 'Active and 'Inactive'
AND client NOT IN
(SELECT DISTINCT client FROM #temp WHERE status = 'Active')
答案 3 :(得分:0)
请尝试以下脚本,
create table #temp (client varchar(50),product int,status varchar(40))
insert intO #TEMP
VALUES('John & Co.',12548,'Active'),
('John & Co.',58451,'Inactive'),
('Vector Inc',12243,'Inactive'),
('Vector Inc',84425,'Active'),
('Ambro Info.',11145,'Inactive'),
('Infy Tech inc',12473,'Inactive'),
('Infy Tech inc',84847,'Inactive'),
('Infy Tech inc',84847,'Active')
SELECT DISTINCT T.client FROM #temp T
WHERE T.client NOT IN(SELECT Z.client FROM #temp Z WHERE z.status='ACTIVE' and T.client=z.client)
and t.status='Inactive'
drop table #TEMP
答案 4 :(得分:0)
您希望每个客户一个结果行,因此您是GROUP BY
个客户。然后只需检查是否只有状态'Inactive'
。如果可能的唯一状态是'Active'
和'Inactive'
,则可以要求最小值:
select client
from mytable
group by client
having min(status) = 'Inactive'
order by client;
对于更多状态,您必须扩展条件,例如and max(status) = 'Inactive'
或and min(status) = max(status)
或and count(distinct status) = 1
或改为使用条件聚合:
having count(case when status = 'Inactive' then 1 end) > 0
and count(case when status = 'Active' then 1 end) = 0
答案 5 :(得分:0)
我只是简单地进行聚合:
SELECT t.client
FROM table t
GROUP BY t.client
HAVING MIN(Status) = MAX(Status) AND MIN(Status) = 'Inactive';