来源表
dbo.sourcetable
该表的列数多于此处显示的列数:
| ID | TrackingID | TrackingTime |....
|--------|----------------|-----------------------|
| 001 | 10 |2017-03-08 10:12:20.240|
| 003 | 50 |2017-03-08 12:30:23.240|
| 001 | 10 |2017-03-03 09:10:23.240|
| 002 | 10 |2017-03-06 10:12:23.240|
| 001 | 15 |2017-03-05 10:12:23.240|
| 001 | 20 |2017-03-08 17:12:23.240|
| 002 | 15 |2017-03-04 00:12:23.240|
| 003 | 10 |2017-03-06 01:18:23.240|
....
我还有一个表格,提供所有可能的TrackingID及其描述。如果这是有用的。
查询
我将最后一个给定的TrackingID计算在一个时间范围内:
--Initializing---------
DECLARE @Begin datetime,
DECLARE @End datetime,
SET @Begin = '2017-03-05 00:00:00';
SET @End = '2017-03-06 00:00:00';
--Coding CTE----------
WITH CTE AS
(
SELECT *
,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY TrackingTime DEC) rn
FROM dbo.sourcetable
WHERE (1 = 1)
AND (TrackingTime BETWEEN @Begin AND @End)
)
--Select CTE----------
SELECT TrackingID
,COUNT(TrackingID) AS TotalIDs
FROM CTE
WHERE (1 = 1)
AND rn = 1
GROUP BY TrackingID
ORDER BY Tracking ID ASC
我收到一个表格,显示每个TrackingID的ID总数:
| TrackingID | TotalIDs |
|------------------|----------------|
| 10 | 12 |
| 15 | 3 |
| 20 | 10 |
...
我想要什么
为了在SSRS中创建图表,我想在很多时间间隔内分割时间范围。然后使用每个区间的开头和结尾作为我的查询的变量输入,最后接收一个表格,该表格显示该区间内每个TrackingID的总ID。
| TrackingTime | 10 | 15 | 20 |...
|-----------------------|----------|----------|----------|
|2017-03-05 00:00:00.000| 13 | 10 | 3 |
|2017-03-05 00:00:02.000| 11 | 8 | 5 |
....
|2017-03-06 00:00:00.000| 20 | 11 | 7 |
查询
DECLARE @TotalTable Table
(
TrackingTime datetime PRIMARY KEY CLUSTERED,
----------------------------
Alle the columns for
the TrackingIDs
----------------------------
)
WHILE @Begin <= @End
BEGIN
INSERT INTO @TotalTable (TrackingTime) VALUES (@Begin)
----------------------------------------
I don't know, so maybe insert
magic code here?!
----------------------------------------
SET @Begin = DATEADD(SS, 120, @Begin)
END;
SELECT *
FROM @TotalTable AS TT
我认为我必须以某种方式使用动态SQL,因为不是每个时间间隔都可以计算。我很抱歉,如果这要求很多。谢谢你的帮助。