在JOIN上计算两个日期之间的行

时间:2016-07-26 12:22:03

标签: tsql sql-server-2014

我有两个名为String和Float的表

String
|               DateAndTime           | Val |
---------------------------------------------
|       2016-07-26 18:35:31.000       | AX2 |
|       2016-07-26 18:30:31.000       | G27 |
|       2016-07-26 18:25:31.000       | AX2 |
|       2016-07-26 18:20:31.000       | AX2 |
|       2016-07-26 18:20:31.000       | G27 |

Float
|               DateAndTime           | Val | Marker |
------------------------------------------------------
|       2016-07-26 18:31:31.000       | 234 |   X    |
|       2016-07-26 18:26:31.000       | 612 |   y    |
|       2016-07-26 18:21:31.000       | 12  |   a    |
|       2016-07-26 18:21:31.000       | 123 |   f    |

从这两个表中,我想从过去24小时内发生的字符串表中的每个Val获取最小和最大日期,并显示该信息。我还想计算在每个Val的最小和最大时间之间插入到浮动表中的每一行,并将其显示在旁边。

以下是我的查询。查询StringTable的部分效果很好,我得到了我期望的结果。然后我尝试在Float表上执行JOIN并计算行数。

    SELECT
    S.Batch,
    COUNT(F.DateAndTime) AS DataPointsRecorded,
    S.CycleStart,
    S.LastRecordedTime
FROM
    (
        SELECT DISTINCT 
                 Val AS Batch,
                 MIN(DateAndTime) AS CycleStart, 
                 MAX(DateAndTime) AS LastRecordedTime
        FROM     dbo.StringTable
        WHERE    DATEDIFF(HOUR,DateAndTime, GETDATE()) < 24
        AND      Val IS NOT NULL
        GROUP BY Val
    ) S 
JOIN     dbo.FloatTable F ON S.CycleStart = F.DateAndTime
GROUP BY S.Batch, S.CycleStart, S.LastRecordedTime
ORDER BY CycleStart desc, Batch

这导致每个DataPointsRecorded出现与每行相同的确切数字。

然后我改变了我使用

加入两个表的方式

JOIN dbo.FloatTable F ON F.DateAndTime BETWEEN S.CycleStart AND S.LastRecordedTime

这只会导致DataPoints的每一行都有非常大的数字。

根据我之前给出的例子,我的预期结果将是这样的。

| Batch | DataPoint |          CycleStart         |               LastRecordedTime        |
-----------------------------------------------------------------------------------------------
|  AX2  |     4     |   2016-07-26 18:20:31.000       |     2016-07-26 18:35:31.000       |
|  G27  |     3     |   2016-07-26 18:20:31.000       |     2016-07-26 18:30:31.000       |

1 个答案:

答案 0 :(得分:1)

尝试这个(我删除了2列CycleStart,LastRecordedTime的小组)

    SELECT
    S.Batch,
    COUNT(F.DateAndTime) AS DataPointsRecorded,
    Min(S.CycleStart) as CycleStart ,
    Max(S.LastRecordedTime) as LastRecordedTime
FROM
    (
        SELECT DISTINCT 
                 Val AS Batch,
                 MIN(DateAndTime) AS CycleStart, 
                 MAX(DateAndTime) AS LastRecordedTime
        FROM     dbo.StringTable
        WHERE    DATEDIFF(HOUR,DateAndTime, GETDATE()) < 24
        AND      Val IS NOT NULL
        GROUP BY Val
    ) S 
JOIN     dbo.FloatTable F ON F.DateAndTime BETWEEN S.CycleStart AND S.LastRecordedTime
GROUP BY S.Batch -- S.CycleStart -- S.LastRecordedTime Commented out the last 2
ORDER BY CycleStart desc, Batch

修改 解释

您在查询中看到更多数据的原因是因为您在更精细的级别聚合它,其中包括时间戳,这会强制sql包含Batch + CycleStart + LastRecordedTime的所有唯一组合