2016-06-08 118 views
1

我试图将一个数据列表填入折线图。我的X轴将是我的StartTime而我的Y轴将是TotalSQL如果数据不存在,则查询一系列数据并返回NULL

想问一下是否可以查询一系列数据, ,采取下面的例子:

|StartTime |Qty | 
----------------------- 
|10   |1  | 
|11   |3  | 
|12   |2  | 
|13   |1  | 
|11   |2  | 

什么是我期望的结果:WHERE子句9中StartTime至12

|StartTime |TOTAL | 
----------------------- 
|9   |NULL | 
|10   |1  | 
|11   |5  | 
|12   |2  | 

谁能告诉我,例如,查询将是什么呢?因为我根本不知道。

+0

你有包含每个可用'StartTime'的表,或者只是假定/暗示,每个小时都存在?这个问题的答案将决定查询结构以及结果查询的简单性或复杂性如何, – gmiley

+0

@gmiley否,表中不包含每一个'StartTime'。 – J4X

回答

1

您可以使用另一张带有Starttime的表格来显示图表。左连接到您的第一个表,然后通过新表的starttime执行一个组。使用计数为您的目的。

TableTimes: 

    | StartTime | 
    -------------- 
    | 9  | 
    | 10  | 
    | 11  | 
    | 12  | 
    | 13  | 
    | 14  | 

Select Sum(Qty) From TableTimes TT 
Left Join FirstTable FT on TT.StartTime=FT.StartTime 
Where TT.StartTime Between 9 and 12 
Group by TT.StartTime 
+0

所以你建议我创建一个'TableTimes'列出所有可用的'StartTime'列? – J4X

+0

是的,这是正确的。列出您希望在图表中显示的所有时间的新表格。 –

1

让您可以通过使用子查询或CTE创建一个全新的表:

select h.Hour, Sum(i.Qty) as Qty 
from ItemsPerHour i 
right outer join (
    select 1 as Hour union all 
    select 2 union all 
    select 3 union all 
    select 4 union all 
    select 5 union all 
    select 6 union all 
    select 7 union all 
    select 8 union all 
    select 9 union all 
    select 10 union all 
    select 11 union all 
    select 12 union all 
    select 13 union all 
    select 14 union all 
    select 15 union all 
    select 16 union all 
    select 17 union all 
    select 18 union all 
    select 19 union all 
    select 20 union all 
    select 21 union all 
    select 24 
) h 
on h.Hour = i.StartTime 
order by h.Hour; 

使用WITHhours CTE:

with hours as 
(
    select 1 as Hour union all 
    select 2 union all 
    select 3 union all 
    select 4 union all 
    select 5 union all 
    select 6 union all 
    select 7 union all 
    select 8 union all 
    select 9 union all 
    select 10 union all 
    select 11 union all 
    select 12 union all 
    select 13 union all 
    select 14 union all 
    select 15 union all 
    select 16 union all 
    select 17 union all 
    select 18 union all 
    select 19 union all 
    select 20 union all 
    select 21 union all 
    select 24 
) 
select h.Hour, Sum(i.Qty) as Qty 
from ItemsPerHour i 
right outer join hours h 
on h.Hour = i.StartTime 
order by h.Hour;