Sql Server组按时间间隔加入零值

时间:2017-03-21 09:10:32

标签: sql sql-server left-join

我有一个以下表格的表格,其中包含日期时间列和ID列(请参阅我的其他问题on SO here)。

    Datum                     SomeID 
2017-01-01 07:44:57.840         1   
2017-01-02 07:45:10.093         2   
2017-01-02 07:45:21.557         3    
2017-01-03 09:07:21.253         2  
2017-01-05 09:07:42.680         1 
2017-01-06 09:07:49.007         5 

我的目标是按时间间隔对行进行分组,在这种情况下不是动态分组,而是按天分组,并计算每天唯一ID的数量。我根据对SO的另一个回应尝试了什么:

Declare @START datetime2;
Set @START = Cast('2016/05/03' as datetime2);

Declare @END datetime2;
Set @END = Cast('2016/06/03' as datetime2);

WITH CTE_Dates AS
(
    SELECT @START AS cte_date
    UNION ALL
    SELECT DATEPART(Year, DATEADD(DAY, 1, cte_date)) as theYear, DATEPART(MONTH, DATEADD(DAY, 1, cte_date)) as theMonth, DATEPART(DAY, DATEADD(DAY, 1, cte_date)) As theDay
    FROM CTE_Dates
    WHERE DATEADD(DAY, 1, cte_date) <= @END
)

SELECT
DATEPART(Year, passageTime) as theYear, DATEPART(MONTH, passageTime) as theMonth, DATEPART(DAY, passageTime) As theDay,
ISNULL(COUNT(Distinct batchNbr), 0) AS counted_batchNbr
FROM [prod].[m1218].[passage]
LEFT JOIN CTE_Dates ON DATEADD(dd, 0, DATEDIFF(dd, 0, passageTime)) = cte_date
WHERE passageTime between @START and @END
GROUP BY DATEPART(Year, passageTime), DATEPART(MONTH, passageTime), DATEPART(DAY, passageTime)
ORDER BY theYear, theMonth, theDay

执行后,我收到以下错误:All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.我认为这是因为我试图在3列(theYear,theMonth,theDay)的行和单个datetime2对象@Start之间创建联合。 / p>

如何修复此问题(可能还有底部部分?),这样当我执行查询时,我会按日获得分组结果,而对于缺失的日期,当天有一个零计数的行? / p>

2 个答案:

答案 0 :(得分:1)

如果我正确理解你要做的事情(获取一个间隔中的所有日期的列表,然后LEFT JOIN到一个表 - 并且,这样,也获得该表中0行的日期) ,我看到CTE的样子是:

WITH CTE_Dates AS
(
SELECT CAST(@START AS date) AS cte_date
UNION ALL
SELECT DATEADD(dd, 1, cte_date)
FROM CTE_Dates
WHERE DATEADD(dd, 1, cte_date) <= CAST(@END AS date))
)

这样,您可以获得DATE数据类型的不同日期。 SELECT应该变得更加容易:

SELECT cte_date, COUNT(Distinct batchNbr) AS counted_batchNbr
FROM CTE_Dates
LEFT JOIN [prod].[m1218].[passage] ON cte_date = CAST(passageTime as DATE) 
GROUP BY cte_date
ORDER BY cte_date

我会尝试复制它以确保它按预期工作。

已编辑 - LEFT JOIN表格顺序

答案 1 :(得分:1)

请尝试此查询:

window.open("New.aspx", "_self"); // will open in the same windows

window.location.href = "New.aspx"; // will open in a new window

Demo here