group by case when

declare @t as table
(
  unionID int,
  userID int ,
  orderID int
)
insert into @t(unionID,userID,orderID)
values
(null,1,100),
(null,2,200),
(2,null,200),
(2,1,300),
(null,3,400),
(3,4,400),
(null,5,500),
(5,4,500),
(null,null,500)
基础数据
select * from @t

 

select 
  case 
    when unionID is not null then unionID 
    else userID 
  end as id
 ,COUNT(orderID) as total
 ,COUNT(distinct orderID) as dis_total
from @t
group by 
  case 
    when unionID is not null then unionID 
    else userID 
  end

 

 

 

select  id
 ,COUNT(orderID) as total
 ,COUNT(distinct orderID) as dis_total
from (
select 
  orderID,
  case 
    when unionID is not null then unionID 
    else userID 
  end as id  
from @t
) as a
group by id

 

posted @ 2020-04-13 23:44  茗::流  阅读(120)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。