加入表格,显示每周的所有记录

时间:2017-01-17 01:38:08

标签: sql sql-server

我希望有人能够帮助我。我有两张桌子,一张是学生姓名,另一张是每个学生每周完成的家庭作业,不是一个真实的例子。只有一名学生做过任何工作。我希望看到一张表格,显示所有学生以及他们做了多少工作(即使每周都是空的。

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,
#Time.Week,
#Time.Year,
#Time.Total

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

我尝试过外部申请 - 但基本上是同样的事情 -

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

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

以上两个查询的输出如下所示 - 与我想要获得的内容 - 每周重复一次,显示所有学生,无论他们是否有任何相关的值。

enter image description here

如果有人可以帮助我,我真的很感激。

2 个答案:

答案 0 :(得分:5)

您需要获取NameWeekYear的所有组合,然后在LEFT JOIN上执行#TIME以获得所需的结果:< / p>

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 :(得分: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