在单个表的两个不同列中显示单个的两个计数

时间:2018-10-24 07:15:32

标签: sql sql-server sql-server-2012

我有一张桌子,记录员工的日常工作。我有一个查询,可以显示每位员工今天的当前工作,还有另一个查询,可以显示每位员工的工作总数。

我想将2个查询合并为一个查询,其中有一个每日列和一个累积列。

我的查询如下:

SELECT staff, 
       process_inprogress, 
       not_yet_completed 
FROM   (SELECT staff, 
               Count(number)    AS Process_InProgress, 
               Count(team_name) AS Not_Yet_Completed 
        FROM   dbo.empty_shell_workflow 
        WHERE  ( end_date IS NULL ) 
               AND ( process_name IS NOT NULL ) 
               AND ( billing_amount IS NULL ) 
               AND ( deletion IS NULL ) 
               AND ( team_name = 'Team Vishma' ) 
               AND ( CONVERT(DATE, start_date) = CONVERT(DATE, Getdate()) ) 
        GROUP  BY staff 
        UNION ALL 
        SELECT staff, 
               Count(number)    AS Process_InProgress, 
               Count(team_name) AS Not_Yet_Completed 
        FROM   dbo.empty_shell_workflow AS Empty_Shell_Workflow_1 
        WHERE  ( team_name = 'Team Vishma' ) 
               AND ( billing_amount IS NULL ) 
               AND ( tag_number IS NULL ) 
               AND ( initiator IS NOT NULL ) 
               AND ( end_date IS NULL ) 
               AND ( deletion IS NULL ) 
               AND ( process_name IS NOT NULL ) 
        GROUP  BY staff) AS t

但是每天和累计都只显示在一个列中

下面是我希望它显示的方式

Staff          Process_Progress(Daily)       Not_YetCompleted(Cumulative)
A                  2                                5
B                  0                                1
C                  6                                8

但是从上面的查询中,累积量显示在每日列中

任何想法,如何修改查询?

1 个答案:

答案 0 :(得分:0)

您可以通过以下情况来尝试以下情况

with cte as
   (    SELECT staff,CONVERT(DATE, start_date)  as date_of_month
                   Count(number)    AS Process_InProgress                       
            FROM   dbo.empty_shell_workflow AS Empty_Shell_Workflow_1 
            WHERE  ( team_name = 'Team Vishma' ) 
                   AND ( billing_amount IS NULL ) 
                   AND ( tag_number IS NULL ) 
                   AND ( initiator IS NOT NULL ) 
                   AND ( end_date IS NULL ) 
                   AND ( deletion IS NULL ) 
                   AND ( process_name IS NOT NULL ) 
            GROUP  BY staff,CONVERT(DATE, start_date)
) select staff, sum(case when date_of_month = CONVERT(DATE, Getdate()) then
             Process_InProgress else 0 end) as Process_Progress_Daily,
         sum(case when date_of_month != CONVERT(DATE, Getdate()) then
             Process_InProgress else 0 end) as Not_YetCompleted
             from cte
             group by staff