计算不同的援助

时间:2015-07-30 18:39:07

标签: sql count distinct

我有以下查询:

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

给出:

  

负责任的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

我想用count(distinct)修改我的查询,以便我可以看到 每个Deliveryname我有多少个独特的PortStatus。

我怎样才能告诉我这个:

  

负责任的DeliveryName独特的PortStatus(es)
  John Doe Peter Smith 4   John Doe Bob Lee 2

2 个答案:

答案 0 :(得分:0)

您想要使用汇总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

答案 1 :(得分:0)

您似乎需要添加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表达式做了什么并不清楚,所以你可能想要在count函数中使用那个表达式,如果你将相同的端口状态分配给不同的PortfolioStatus值。