之前可能已经回答过这个问题,但我甚至不确定如何搜索它,所以如果它重复,我会道歉。
我有一张电话。列包括呼叫开始的时间,呼叫的长度(以秒为单位)以及"频道"电话进来(1-4的整数)。我想知道所有4个频道被占用的频率。我该如何查询?
例如,考虑样本数据:
CallTime Length Channel
12:00 22 1
12:05 15 2
12:10 20 3
12:15 10 4
在这种情况下,所有4个频道都被占用了7分钟(直到第一个呼叫结束)。有没有办法查询这个?
谢谢,
-Scott
答案 0 :(得分:0)
DECLARE @MyTable TABLE
(
CallTime DATETIME,
CallLength INT,
Channel INT
)
INSERT INTO @MyTable
( CallTime, CallLength, Channel )
VALUES
( '06-26-2014 12:00:00', 22, 1 ),
( '06-26-2014 12:00:05', 15, 2 ),
( '06-26-2014 12:00:10', 20, 3 ),
( '06-26-2014 12:00:15', 10, 4 );
DECLARE @number_of_numbers INT = 100000;
;WITH
a AS (SELECT 1 AS i UNION ALL SELECT 1),
b AS (SELECT 1 AS i FROM a AS x, a AS y),
c AS (SELECT 1 AS i FROM b AS x, b AS y),
d AS (SELECT 1 AS i FROM c AS x, c AS y),
e AS (SELECT 1 AS i FROM d AS x, d AS y),
f AS (SELECT 1 AS i FROM e AS x, e AS y),
numbers AS
(
SELECT TOP(@number_of_numbers)
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS number
FROM f
)
SELECT
d.CheckTime,
MAX(CASE WHEN m.Channel = 1 THEN 1 ELSE 0 END) Channel1,
MAX(CASE WHEN m.Channel = 2 THEN 2 ELSE 0 END) Channel2,
MAX(CASE WHEN m.Channel = 3 THEN 3 ELSE 0 END) Channel3,
MAX(CASE WHEN m.Channel = 4 THEN 4 ELSE 0 END) Channel4
FROM
(
SELECT DATEADD(SECOND, n.number, '06/26/2014') CheckTime
FROM numbers n
) AS d
INNER JOIN @MyTable m
ON d.CheckTime >= m.CallTime AND d.CheckTime <= DATEADD(SECOND, m.CallLength, m.CallTime)
GROUP BY d.CheckTime
下面是一个示例,您可以在其中创建一个数字表,然后使用它创建一天中每一秒的时间段,然后您可以加入您的表并使用group by您可以找到所有的通道活性