使用零填充SQL查询中的日期间隔

时间:2016-10-05 10:52:20

标签: sql sql-server tsql

我有以下结构(来自表等的一些连接),这些结构将用于生成图表。

有些ID没有所有日期的数据,导致图表中出现一些虚线。

问题是,如何为每个ID添加缺少的日期并用零填充其数据单元?

enter image description here

作为剧本:

(67, '2016-09-28 00:00:00.000',1),
(178, '2016-09-28 00:00:00.000',6),
(42, '2016-09-25 00:00:00.000',1),
(66, '2016-09-25 00:00:00.000',122),
(67, '2016-09-25 00:00:00.000',2),
(10, '2016-09-24 00:00:00.000',5),
(13, '2016-09-24 00:00:00.000',4),
(66, '2016-09-24 00:00:00.000',198),
(67, '2016-09-24 00:00:00.000',15),
(178, '2016-09-24 00:00:00.000',4),
(10, '2016-09-23 00:00:00.000',1),
(13, '2016-09-23 00:00:00.000',2),
(42, '2016-09-23 00:00:00.000',4),
(66, '2016-09-23 00:00:00.000',208),
(67, '2016-09-23 00:00:00.000',15)

3 个答案:

答案 0 :(得分:1)

这是一种方法:

with t as (
      <your query here>
     )
select i.id, rt.roundedtime, coalesce(data, 0) as data
from (select distinct id from t) i cross join
     (select distinct roundedtime rt from t) rt left join
     t
     on t.id = i.id and t.roundedtime = rt.roundedtime;

换句话说,使用id创建日期列表和cross join。然后使用left join引入您的数据。

此查询使用原始数据上的select distinct来获取日期和ID列表。可能有更有效的方法来获取每个列表。

答案 1 :(得分:1)

日历表和CROSS JOIN的另一种方式:

;WITH YourQueryOutput AS (
--put your select statement here
), calendar AS (
SELECT  CAST(MIN(RoundedTime) as datetime) as d,
        MAX(RoundedTime) as e
FROM YourQueryOutput
UNION ALL
SELECT  DATEADD(day,1,d),
        e
FROM calendar
WHERE d < e
)

SELECT  t.ID,
        c.d,
        COALESCE(t1.[data],0) as [data]
FROM calendar c
CROSS JOIN (
    SELECT DISTINCT ID
    FROM YourQueryOutput
    ) t
LEFT JOIN YourQueryOutput t1
    ON t.ID = t1.ID and t1.RoundedTime = c.d
ORDER BY t.ID, c.d
OPTION(MAXRECURSION 0)

您提供的样本的输出

ID  d                       data
10  2016-09-23 00:00:00.000 1
10  2016-09-24 00:00:00.000 5
10  2016-09-25 00:00:00.000 0
10  2016-09-26 00:00:00.000 0
10  2016-09-27 00:00:00.000 0
10  2016-09-28 00:00:00.000 0
...
178 2016-09-23 00:00:00.000 0
178 2016-09-24 00:00:00.000 4
178 2016-09-25 00:00:00.000 0
178 2016-09-26 00:00:00.000 0
178 2016-09-27 00:00:00.000 0
178 2016-09-28 00:00:00.000 6

答案 2 :(得分:0)

您可以在使用连接的SELECT语句中检查 ISNULL(YourDataColumn,0)

示例:

SELECT
    Q.QuestionId,
    Q.SenderType,
    ISNULL(Q.Data,0) AS Data
FROM @tblQuestion Q
LEFT JOIN @tblTeacher T ON Q.SenderId=T.Id AND Q.SENDERTYPE='TEACHER'
LEFT JOIN @tblInstitute I ON Q.SenderId=I.Id AND Q.SENDERTYPE='INSTITUTE'
如果在加入

之后没有可用数据,

IN上面的Select Statement Data column return 0