选择子查询的计数而不是使用'和'过滤

时间:2018-05-29 16:37:35

标签: sql sql-server

我有以下查询,运行完美。但是,您会注意到注释行,我在其中指定了筛选结果的特定条件。而不是必须取消注释该行,并再次运行查询,有没有办法将其结果添加为列,所以我只需要运行一次?

select 
du.USERID as 'Username', 
du.LIBRARYNAME as 'Home Office', 
count(*) as 'Documents created'
from mhgroup.dochistory dh (nolock)
inner join mhgroup.DOCMASTER dm (nolock)
on (dh.DOCNUM=dm.DOCNUM and dh.VERSION=dm.VERSION)
inner join mhgroup.DOCUSERS du (nolock)
on dh.DOCUSER=du.USERID
where (dh.activity_datetime >= dateadd(dd,-365, getutcdate()))
and du.LIBRARYNAME in ('DEN','HOU')
and dm.TYPE = 'd'
and dh.ACTIVITY = 'Create'
--and dm.C1ALIAS like '9999%'
group by du.USERID, du.LIBRARYNAME
order by count(*) desc

现在,结果如下:

Username    Home Office Documents created
User1       HOU         1520
User2       HOU         475
User3       DEN         182
User4       DEN         54

我试图让它们看起来像这样:

Username    Home Office Documents created Non-Billable Docs
    User1       HOU         1520          500
    User2       HOU         475           250
    User3       DEN         182           82
    User4       DEN         54            34

2 个答案:

答案 0 :(得分:2)

您可以使用包含SUM的案例表达式。

我会告诉你关于NOLOCK的事。使用该提示几乎不是一个好主意。那么多坏事。并且不推荐使用WITH关键字作为查询提示。 https://blogs.sentryone.com/aaronbertrand/bad-habits-nolock-everywhere/

您可能还想看一眼。
https://sqlblog.org/2011/09/20/bad-habits-to-kick-using-shorthand-with-date-time-operations

select 
    du.USERID as 'Username', 
    du.LIBRARYNAME as 'Home Office', 
    count(*) as 'Documents created'
    , NonBillableDocs = sum(case when dm.C1ALIAS like '9999%' then 1 else 0 end)
from mhgroup.dochistory dh (nolock)
inner join mhgroup.DOCMASTER dm (nolock) on (dh.DOCNUM=dm.DOCNUM and dh.VERSION=dm.VERSION)
inner join mhgroup.DOCUSERS du (nolock) on dh.DOCUSER=du.USERID
where (dh.activity_datetime >= dateadd(dd,-365, getutcdate()))
    and du.LIBRARYNAME in ('DEN','HOU')
    and dm.TYPE = 'd'
    and dh.ACTIVITY = 'Create'
    --and dm.C1ALIAS like '9999%'
group by du.USERID
    , du.LIBRARYNAME
order by count(*) desc

答案 1 :(得分:1)

您可以将其添加为SUM:

SELECT du.USERID AS 'Username'
     , du.LIBRARYNAME AS 'Home Office'
     , COUNT(*) AS 'Documents created'
     , SUM(   CASE
                  WHEN dm.C1ALIAS LIKE '9999%' THEN
                      1
                  ELSE
                      0
              END
          ) AS [Non-Billable Docs]
FROM mhgroup.dochistory dh
    (NOLOCK)
    INNER JOIN mhgroup.DOCMASTER dm
    (NOLOCK) ON (
                    dh.DOCNUM = dm.DOCNUM
                    AND dh.VERSION = dm.VERSION
                )
    INNER JOIN mhgroup.DOCUSERS du
    (NOLOCK) ON dh.DOCUSER = du.USERID
WHERE (dh.activity_datetime >= DATEADD(dd, -365, GETUTCDATE()))
      AND du.LIBRARYNAME IN ( 'DEN', 'HOU' )
      AND dm.TYPE = 'd'
      AND dh.ACTIVITY = 'Create'
GROUP BY du.USERID
       , du.LIBRARYNAME
ORDER BY COUNT(*) DESC;