7

我创建了以下存储过程,用于计算所选位置的特定范围之间每天的记录数:

[dbo].[getRecordsCount] 
@LOCATION as INT,
@BEGIN as datetime,
@END as datetime

SELECT
ISNULL(COUNT(*), 0) AS counted_leads, 
CONVERT(VARCHAR, DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp)), 3) as TIME_STAMP 
FROM HL_Logs
WHERE Time_Stamp between @BEGIN and @END and ID_Location = @LOCATION
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp))

但问题是结果没有显示记录为零的日子,我很确定这与我的 WHERE 语句不允许显示零值有关,但我不知道如何解决这个问题.

提前感谢尼尔

4

4 回答 4

9

与其说是 WHERE 子句,不如说是 GROUP BY。该查询将只返回存在的行的数据。这意味着当您按时间戳日期分组时,只会返回有行的日期。SQL Server 无法从上下文中知道您要“填空”,它也不知道用什么。

正常的答案是一个 CTE,它会产生你想看到的所有日子,从而填补空白。这有点棘手,因为它需要一个递归 SQL 语句,但这是一个众所周知的技巧:

WITH CTE_Dates AS
(
    SELECT @START AS cte_date
    UNION ALL
    SELECT DATEADD(DAY, 1, cte_date)
    FROM CTE_Dates
    WHERE DATEADD(DAY, 1, cte_date) <= @END
)
SELECT
cte_date as TIME_STAMP,
ISNULL(COUNT(HL_Logs.Time_Stamp), 0) AS counted_leads, 
FROM CTE_Dates
LEFT JOIN HL_Logs ON DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp)) = cte_date
WHERE Time_Stamp between @BEGIN and @END and ID_Location = @LOCATION
GROUP BY cte_date

分解它,CTE 使用一个引用自身的联合来递归地将一天一次添加到前一个日期,并将该日期作为表格的一部分记住。如果您运行一个使用 CTE 的简单语句并从中选择 *,您会看到开始和结束之间的日期列表。然后,该语句根据日志时间戳日期将此日期列表连接到日志表,同时使用左连接保留没有日志条目的日期(从“左侧”获取所有行,无论它们在“右”侧与否)。最后,我们按日期分组并计数,我们应该得到您想要的答案。

于 2012-09-11T15:11:12.403 回答
4

当没有数据要计算时,就没有要返回的行。

如果您想将空天包含为 0,则需要创建一个表(或临时表或子查询)来存储天数,并从中加入查询。

例如:类似的东西

SELECT 
    COUNT(*) AS counted_leads,  
    CONVERT(VARCHAR, DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp)), 3) as TIME_STAMP  
    FROM 
        TableOfDays
           left join
        HL_Logs 
           on TableOfDays.Date = convert(date,HL_Logs.Time_Stamp)
           and ID_Location = @LOCATION 
    WHERE TableOfDays.Date between @BEGIN and @END 
    GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, Time_Stamp)) 
于 2012-09-11T15:08:32.803 回答
0

使用左外连接。如

select count(stuff_ID), extra_NAME 
from dbo.EXTRAS 
left outer join dbo.STUFF on suff_EXTRA = extra_STUFF 
group by extra_NAME 
于 2015-09-18T17:35:28.407 回答
0

我最近有一个类似的任务,并以此作为我工作的背景。但是,正如 robwilliams 我也解释的那样,无法使其 KeithS 解决方案正常工作。我的任务与我的工作时间略有不同,但我认为 neilrudds 问题的解决方案是

DECLARE @Start as DATETIME
       ,@End as DATETIME
       ,@LOCATION AS INT;


WITH CTE_Dates AS
(
    SELECT @Start AS cte_date, 0 as 'counted_leads'
    UNION ALL
    SELECT DATEADD(DAY, 1, cte_date) as cte_date, 0 AS 'counted_leads'
    FROM CTE_Dates  
    WHERE DATEADD(DAY, 1, cte_date) <= @End
)
SELECT cte_date AS 'TIME_STAMP'
      ,COUNT(HL.ID_Location) AS 'counted_leads'
FROM CTE_Dates 
LEFT JOIN HL_Logs AS HL ON CAST(HL.Time_Stamp as date) = CAST(cte_date as date)
AND DATEPART(day, HL.Time_Stamp) = DATEPART(day,cte_date)
AND HL.ID_Location = @LOCATION
group by cte_date
OPTION (MAXRECURSION 0)
于 2016-09-27T15:10:01.700 回答