简体   繁体   中英

Complicated query involving res

I have the table as below and I need to have the query how many tasks created for the day and how many are resolved and I need to capture the Tasks which are passed from previous day with active status. Ex: TaskId 101 is created on 11/10/2014 and it is resolved on 11/12/2014 so it should show in the count of 11/11/2014 and 11/12/2014 also.

TaskId CreateDate Status ResolvedDate
101 11/10/2014 Resolved 11/12/2014
102 11/10/2014 Resolved 11/10/2014
103 11/11/2014 Active NULL 
104 11/11/2014 Resolved 11/13/2014
105 11/13/2014 Active 11/13/2014

Please help me as I am not able to think of any solution. Sorry I was trying to post the table schema in table format but not able to create table and I am new to this forum.

you can get the result using case based aggregation

The CTE generates list of dates for a given range.

For each day, total active ( created that day and created previously but not resolved) and total resolved that day are calculated using case , max and group by

declare @start_date datetime = '2014-11-10'
declare @end_date datetime ='2014-11-13'


;WITH CTE AS
(
    SELECT @start_date AS date
    UNION ALL
    SELECT DATEADD(day, 1, date) as date
    FROM CTE
    WHERE DATEADD(day, 1, date) <= @end_date
)
select cte.date,
       sum( case when  createDate <= cte.date and ( resolveddate is null or  ResolvedDate >= cte.date) then 1 else 0 end
          ) as TotalActive,

       sum( case when cte.date = ResolvedDate then 1 else 0 end
          ) as TotalResolved
from cte
left join Table1 T
ON T.createDate <= cte.date
GROUP BY CTE.DATE

@radar, You just gave me the hope with the query and I have changed the query as below and it started showing result. But the TotalActive showing less value than TotalCreated.

declare @start_date datetime = getdate()-30
declare @end_date datetime = getdate()
;WITH CTE AS
(
    SELECT @start_date AS date
    UNION ALL
    SELECT DATEADD(day, 1, date) as date
    FROM CTE
    WHERE DATEADD(day, 1, date) <= @end_date
)
select cte.date,
        sum( case when CONVERT(varchar, CreateDate, 101) <= CONVERT(varchar, cte.date, 101) and CONVERT(varchar, cte.date, 101) <= CONVERT(varchar, ResolveDate, 101) then 1 else 0 end
          ) as TotalActive,
          sum( case when  CONVERT(varchar, cte.date, 101) = CONVERT(varchar, CreateDate, 101) then 1 else 0 end
          ) as TotalCreated,
       sum( case when CONVERT(varchar, cte.date, 101) = CONVERT(varchar, ResolveDate, 101) then 1 else 0 end
          ) as TotalResolved

from cte
left join [WarehouseIncidents] T
ON CONVERT(varchar, CreateDate, 101) >= CONVERT(varchar, cte.date, 101)

GROUP BY CTE.DATE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM