ОК. Один (по общему признанию, отвратительный) способ сделать это, чтобы создать udf, который вычисляет счетчик открытых дней для данного дня следующим образом:
CREATE FUNCTION [dbo].[fn_open_alert_count] (@date date)
RETURNS int
AS
BEGIN
RETURN (SELECT COUNT(intContextID) as opencount FROM tblState WHERE strToStateName = 'Unassigned' AND datTimeStamp <= @date) - (SELECT COUNT(intContextID) as closedcount FROM tblState WHERE strToStateName = 'Closed' AND datTimeStamp <= @date)
END
Тогда вы можете сделать запрос так:
DECLARE @StartDate DATETIME = '2009-10-10';
DECLARE @EndDate DATETIME = '2009-10-15 23:59:59';
WITH AllDays
AS (
SELECT @StartDate AS [Date]
, 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
, [level] + 1
FROM AllDays
WHERE [Date] < @EndDate
)
SELECT CAST(AllDays.[Date] AS DATE) AS 'DATE'
, datename(dw, AllDays.[Date]) AS 'DAY'
,[dbo].[fn_open_alert_count](AllDays.[Date])
FROM AllDays
Если у вас нет разрешения на создание функций, вы можете встроить функциональность следующим образом:
DECLARE @StartDate DATETIME = '2009-10-10';
DECLARE @EndDate DATETIME = '2009-10-15 23:59:59';
WITH AllDays
AS (
SELECT @StartDate AS [Date]
, 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
, [level] + 1
FROM AllDays
WHERE [Date] < @EndDate
)
SELECT CAST(AllDays.[Date] AS DATE) AS 'DATE'
, datename(dw, AllDays.[Date]) AS 'DAY'
,(SELECT COUNT(intContextID) as opencount FROM tblState WHERE strToStateName = 'Unassigned' AND datTimeStamp <= AllDays.[Date]) - (SELECT COUNT(intContextID) as closedcount FROM tblState WHERE strToStateName = 'Closed' AND datTimeStamp <= AllDays.[Date]) AS TOTAL_OPEN
FROM AllDays
Это дает мне следующий вывод:
DATE DAY TOTAL_OPEN
2009-10-10 Saturday 0
2009-10-11 Sunday 1
2009-10-12 Monday 1
2009-10-13 Tuesday 1
2009-10-14 Wednesday 0
2009-10-15 Thursday 0
2009-10-16 Friday 0