【问题标题】:Count Distinct Assistance计数不同的援助
【发布时间】:2015-07-30 18:39:07
【问题描述】:

我有以下疑问:

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

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

我怎样才能让它给我看这个:

负责的    DeliveryName    唯一端口状态
John Doe        彼得·史密斯         4
John Doe        Bob Lee               2

【问题讨论】:

  • 似乎您已经知道 COUNT (DISTINCT),那么当您尝试它时发生了什么?你收到错误了吗?
  • 我得到 4 个而不是 (4)

标签: sql count distinct


【解决方案1】:

您想使用聚合 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

【讨论】:

    【解决方案2】:

    看起来您需要在 group by 子句中添加 count(disctinct p.PortfolioStatus) 并删除 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 值,您可能希望在 count 函数中使用该表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2012-05-04
      • 1970-01-01
      • 2022-06-11
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多