返回数据,即使没有记录存在SQL Server

时间:2018-12-05 11:34:32

标签: sql-server tsql

我有一个叫“学生”的表,即使某个特定课程,特定年份的数据不存在,我也会得到记录。

这是我的数据:

CREATE TABLE students ([Year] int,
                       Course varchar(50),
                       [Number of students] int);

INSERT INTO students
VALUES (2018, 'Maths ', 10),
       (2019, 'Maths', 15),
       (2018, 'Economics', 8),
       (2018, 'Social Studies', 3),
       (2019, 'Social Studies', 4),
       (2018, 'Science', 7);

如何获得这样的输出:

Year    Course  Students
2018    Maths   10
2019    Maths   15
2018    Economics   8
2019    Economics   0
2018    Social Studies  3
2019    Social Studies  4
2018    Science 7
2019    Science 0

如果使用where子句(例如,“ incourses”,“ maths”)中的where路线,请不要手动编写代码值。想在SQL Server中使用变量。

谢谢。

2 个答案:

答案 0 :(得分:2)

您可以加入日历表:

WITH years AS (
    SELECT 2018 AS Year UNION ALL
    SELECT 2019
),
courses AS (
    SELECT 'Maths' AS Course UNION ALL
    SELECT 'Economics' UNION ALL
    SELECT 'Social Studies' UNION ALL
    SELECT 'Science'
)

SELECT
    y.Year,
    c.Course,
    COALESCE(s.Students, 0) AS Students
FROM year y
CROSS JOIN courses c
LEFT JOIN Students s
    ON s.Year = y.Year AND s.Course = c.Course;

答案 1 :(得分:1)

这可以为您提供所需的结果,但是,DISTINCT的表很大,可能会变得昂贵:

SELECT Y.[Year],
       C.Course,
       ISNULL(S.[Number of students],0) AS [Number of students]
FROM (SELECT DISTINCT [Year] FROM dbo.students) Y
     CROSS JOIN (SELECT DISTINCT Course FROM dbo.students) C
     LEFT JOIN dbo.students S ON Y.[Year] = S.[Year]
                             AND C.Course = S.Course;

理想情况下,您应该有一个单独的表,其中包含您的Year和Course数据,然后可以将查询“简化”为:

SELECT Y.[Year],
       C.Course,
       ISNULL(S.[Number of students],0) AS [Number of students]
FROM dbo.Years Y
     CROSS JOIN dbo.Courses C
     LEFT JOIN dbo.students S ON Y.[Year] = S.[Year]
                             AND C.Course = S.Course;