如何在使用group by的单个查询中获取多个计数记录以及其他记录

时间:2017-06-16 08:31:29

标签: sql sql-server-2008

如果用户名存在,如果用户名不存在,我想在用户名条件下选择某个文件名,日期,学位名称的特定文件名,日期,学位名称的总数,已完成名和重命名数

----------------------------------------
file_nm | degree_nm| date_nm  | user_nm
----------------------------------------
X       | D_x      |02/05/2013| USER3
X       | D_x      |02/05/2014| NULL
Y       | D_y      |02/05/2012| USER1
z       | D_z      |02/05/2015| NULL
Y       | D_y      |02/05/2013| USER1
z       | D_z      |02/05/2012| USER2

我想要file_nm,degree_nm,date_nm明智计算总文件,剩余文件,已完成

file total for x is 2 remaining for x is 1 completed file is 1

我在多个单个查询中获得了正确的值,但我想将其作为整体

select filenm,degree_name,date_name,COUNT(*) as total
from sameTable
group by filenm,degree_name,date_name

select filenm,degree_name,date_name,COUNT(*) as remaining
from sameTable
group by filenm,degree_name,date_name,username
having username is null
select  filenm,degree_name,date_name,COUNT(*) as completed
from sameTable
group by filenm,degree_name,date_name,username
having username is not null

我想要的o / p

filenm,degree_name,date_name,total,remaining,completed

2 个答案:

答案 0 :(得分:0)

案件总和:

select filenm,
       degree_name,
       date_name, 
       COUNT(*) as total,
       sum(case when username is null then 1 else 0 end) as remaining,
       sum(case when username is not null then 1 else 0 end) as complete
from sameTable
group by filenm,degree_name,date_name

答案 1 :(得分:0)

select filenm
    ,degree_name
    ,date_name
    ,total = COUNT(*)
    ,remaining = COUNT(DISTINCT CASE WHEN username is null THEN username ELSE NULL END)
    ,completed = COUNT(DISTINCT CASE WHEN username is not null THEN username ELSE NULL END)
from sameTable
group by filenm,degree_name,date_name