【问题标题】:How to get multiple count record along with other record in a single query in which group by is used如何在使用 group by 的单个查询中获取多个计数记录以及其他记录
【发布时间】:2017-06-16 08:31:28
【问题描述】:

我想根据用户名的条件从某个文件名、日期、学位名称中选择总、已完成和重命名数据,如果用户名存在,则计为已完成,如果用户名不存在,则计为剩余

p>
----------------------------------------
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

【问题讨论】:

  • 这不是你使用having的方式
  • @JohnHC 感谢 john 注意到这一点,不知道我为什么使用它 :-)。我的错。

标签: sql sql-server-2008


【解决方案1】:

案例总和:

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

【讨论】:

  • 只是“,”在总数之后丢失,否则一切都按我的意愿工作,谢谢
【解决方案2】:
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

【讨论】:

  • 感谢朋友的时间和精力。但我没有得到我想要的。我得到 0 剩余的每个文件和 0/1 的已完成,顺便说一下你的总数是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-29
相关资源
最近更新 更多