Sql 在Oracle中检索具有一个条目的行
我有一个表订单,其中有许多销售订单和许多客户,通常是同一客户的许多订单。但我试图找到针对单个客户的订单,我不想看到针对同一客户的多个订单。我的例子可能会有所帮助Sql 在Oracle中检索具有一个条目的行,sql,oracle,Sql,Oracle,我有一个表订单,其中有许多销售订单和许多客户,通常是同一客户的许多订单。但我试图找到针对单个客户的订单,我不想看到针对同一客户的多个订单。我的例子可能会有所帮助 ╔══════════╦══════════════╗ ║ Customer ║ Order Number ║ ╠══════════╬══════════════╣ ║ ABC ║ 123 ║ ║ ABC ║ 456 ║ ║ XYZ ║ 789 ║ ║
╔══════════╦══════════════╗
║ Customer ║ Order Number ║
╠══════════╬══════════════╣
║ ABC ║ 123 ║
║ ABC ║ 456 ║
║ XYZ ║ 789 ║
║ MNO ║ 987 ║
║ XYZ ║ 654 ║
╚══════════╩══════════════╝
因此,在本例中,我只想看到客户MNO和订单号987,因为该客户只有一个条目。Hmmm,您可以使用聚合来完成此操作:
select customer, min(OrderNumber) as OrderNumber
from t
group by customer
having count(*) = 1;
只有一行时,min返回该行上的订单号
另一种方法不存在:
这样做的好处是可以检索更多的列。请尝试以下方法
with tbl (Customer,Order_Number) as
(select 'ABC',123 from dual union all
select 'ABC',456 from dual union all
select 'XYZ',789 from dual union all
select 'MNO',987 from dual union all
select 'XYZ',654 from dual)
--recreating the source table
select customer,Order_Number from (
select t.*, count(customer) over (partition by customer) as cnt from tbl t)
where cnt =1
with tbl (Customer,Order_Number) as
(select 'ABC',123 from dual union all
select 'ABC',456 from dual union all
select 'XYZ',789 from dual union all
select 'MNO',987 from dual union all
select 'XYZ',654 from dual)
--recreating the source table
select customer,Order_Number from (
select t.*, count(customer) over (partition by customer) as cnt from tbl t)
where cnt =1