2017-01-17 68 views
3

我希望有人能夠幫助我。我有兩張桌子,一張是學生名字,另一張是每個學生每週都做的作業量(不是一個真實的例子)。只有一名學生做了任何工作。我希望看到一個圖表,顯示所有學生和多少工作,他們所做的(即使是空,每個星期加入顯示每週所有記錄的表格

CREATE TABLE #NAME (Name VARCHAR(20)) 

INSERT INTO #NAME VALUES 
('John'),('Tom'),('Jack') 

CREATE TABLE #TIME (Name VARCHAR(20), Week INT, Year INT, Total INT) 

INSERT INTO #TIME VALUES 
('John',1,2017,34),('John',2,2017,24),('John',3,2017,65),('John',4,2017,22),('John',5,2017,45) 

我想到了一個左外連接將工作 - 但它只是引用但本質上得到同樣的事情 - -

SELECT 
#Name.Name, 
A.Week, 
A.Year, 
A.Total 

FROM #NAME OUTER APPLY (SELECT * FROM #TIme WHERE #Name.Name = #Time.Name) A 

從上面的兩個查詢的輸出如下所示 - 名稱,而不是幾周

SELECT 
#Name.Name, 
#Time.Week, 
#Time.Year, 
#Time.Total 

FROM #NAME LEFT OUTER JOIN #Time ON #NAME.Name = #Time.Name 

我嘗試了外部應用之間的連接旁邊什麼我tryi每週重複一遍,向所有學生展示,不管他們是否有任何關聯值。

enter image description here

我會非常感激,如果有人可以幫助我。

回答

5

你需要得到的Name所有組合,Week,並Year然後在#TIMELEFT JOIN以獲得期望的結果:

WITH CteNameWeekYear(Name, [Week], [Year]) AS(
    SELECT 
     n.*, t.* 
    FROM(
     SELECT DISTINCT [Week], [Year] FROM #TIME 
    ) t 
    CROSS JOIN #Name n 
) 
SELECT 
    c.Name, 
    c.[Week], 
    c.[Year], 
    t.Total 
FROM CteNameWeekYear c 
LEFT JOIN #TIME t 
    ON c.Name = t.Name 
    AND c.[Year] = t.[Year] 
    AND c.[Week] = t.[Week] 
ORDER BY c.[Year], c.[Week], c.Name; 

ONLINE DEMO

1

試試這個

WITH cte AS (
    SELECT DISTINCT t.Week, t.Year 
    FROM #TIME t 
), cte1 AS (
    SELECT n.Name, cte.Week, cte.Year 
    FROM #NAME n 
    CROSS JOIN cte 
) 
SELECT 
    n.Name, n.Week, n.Year, t.Total 
FROM 
    cte1 n 
    LEFT JOIN #TIME t ON n.NAME = t.NAME AND n.Week = t.Week AND n.Year = t.Year 
相關問題