2016-06-08 85 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; 
相關問題