计数不同的帮助

Count Distinct Assistance

我有以下查询:

select c2.Responsible, c.deliveryname,
case..... --conditions here
end as 'PortStatus'
from table p
join table c
on p.OwnerContactID = c.ContactID
join table c2
on c.ContactID = c2.ContactID
where p.PortfolioStatus <>''
and c2.responsible <> ''
group by c.deliveryname, p.PortfolioStatus, c2.responsible

给出:

Responsible  DeliveryName  PortStatus
John Doe      Peter Smith      DI
John Doe      Peter Smith      EE
John Doe      Peter Smith      hy
John Doe      Peter Smith      pw
John Doe      Bob Lee           pw
John Doe      Bob Lee           pw
John Doe      Bob Lee           ss

我想用一个计数(不同的)修改我的查询,以便我可以看到 每个 Deliveryname 我有多少个唯一的 PortStatus。

我怎样才能让它显示这个:

Responsible    DeliveryName    Unique PortStatus(es)
John Doe        Peter Smith         4
John Doe        Bob Lee               2

您想使用聚合 COUNTDISTINCT 关键字。您还需要按 portStatus 删除分组,否则每行的结果始终为 1。

select c2.Responsible, c.deliveryname,
COUNT(DISTINCT (case..... --conditions here end)) as 'Unique PortStatus(es)'
from table p
join table c on p.OwnerContactID = c.ContactID
join table c2 on c.ContactID = c2.ContactID
where p.PortfolioStatus <>'' and c2.responsible <> ''
group by c.deliveryname,  c2.responsible

看起来您需要添加 count(disctinct p.PortfolioStatus) 并从 group by 子句中删除 p.PortfolioStatus

select 
  c2.Responsible, 
  c.deliveryname, 
  count(disctinct p.PortfolioStatus) as "Unique PortStatus(es)"
from table p
join table c
  on p.OwnerContactID = c.ContactID
join table c2
  on c.ContactID = c2.ContactID
where p.PortfolioStatus <>''
  and c2.responsible <> ''
group by c.deliveryname, c2.responsible

不清楚你的 case 表达式做了什么,因为你遗漏了那部分,所以如果你将相同的端口状态分配给不同的 PortfolioStatus 值,你可能想在计数函数中使用该表达式。