在两个不同的表中使用FK时查找最小日期时间

时间:2017-01-11 08:24:51

标签: sql-server tsql join foreign-keys

我有两张桌子:

COURSE
------
Id
Name

TEST
------
Id
CourseId (FK to `COURSE.ID`)
DATETIME
NUMBERS

假设COURSE表包含ID 1,2(仅2列)和TEST表,其中8个数据的数据具有不同的DATETIMECourseId 1(3列)和2(6列)。

我希望通过加入这两个表来找到最小DATETIME,CourseIDName。以下查询给出了2输出:

(SELECT  min([DATETIME]) as DATETIME ,[TEST].CourseID,Name
    FROM [dbo].[TEST]
    left JOIN [dbo].[COURSE]
    ON [dbo].[TEST].CourseID=[COURSE].ID GROUP BY CourseID,Name) 

我想要一个单列输出,即单个输出列(最小日期时间以及名称和ID)..我如何实现?

2 个答案:

答案 0 :(得分:0)

有2门课程,你加入这样的课程时总会得到2排。它将为您提供每门课程的最低日期值。第一种方法是在查询中使用TOP 1,这样就可以为您提供最早的测试日期。另一种方法是使用WHERE子句通过单个过程对其进行过滤。

请运行此示例代码,其中包含您可以执行的操作的一些变体,注释中包含的注释:

CREATE TABLE #course ( id INT, name NVARCHAR(20) );

CREATE TABLE #Test
    (
      id INT ,
      courseId INT ,
      testDate DATETIME -- you shouldn't use a keyword for a column name
    );

INSERT  INTO #course
        ( id, name )
VALUES  ( 1, 'Maths' ),
        ( 2, 'Science' );

-- note I used DATEADD(HOUR, -1, GETDATE()) to simply get some random datetime values
INSERT  INTO #Test
        ( id, courseId, testDate )
VALUES  ( 1, 1, DATEADD(HOUR, -1, GETDATE()) ),
        ( 2, 1, DATEADD(HOUR, -2, GETDATE()) ),
        ( 3, 1, DATEADD(HOUR, -3, GETDATE()) ),
        ( 4, 2, DATEADD(HOUR, -4, GETDATE()) ),
        ( 5, 2, DATEADD(HOUR, -5, GETDATE()) ),
        ( 6, 2, DATEADD(HOUR, -6, GETDATE()) ),
        ( 7, 2, DATEADD(HOUR, -7, GETDATE()) ),
        ( 8, 2, DATEADD(HOUR, -8, GETDATE()) );

-- returns minumum date for each course - 2 rows
SELECT  MIN(t.testDate) AS TestDate ,
        t.courseId ,
        c.name
FROM    #Test t 
        -- used inner join as could see no reason for left join
        INNER JOIN #course c ON t.courseId = c.id
GROUP BY courseId , name;

-- to get course with minimum date - 1 row
SELECT TOP 1
        MIN(t.testDate) AS TestDate ,
        t.courseId ,
        c.name
FROM    #Test t 
        -- used inner join as could see no reason for left join
        INNER JOIN #course c ON t.courseId = c.id
GROUP BY t.courseId , c.name
ORDER BY MIN(t.testDate); -- requires order by

-- to get minimum date for a specified course - 1 row
SELECT  MIN(t.testDate) AS TestDate ,
        t.courseId ,
        c.name
FROM    #Test t 
        -- used inner join as could see no reason for left join
        INNER JOIN #course c ON t.courseId = c.id
WHERE t.courseId = 1 -- requires you specify a course id
GROUP BY courseId , name;

DROP TABLE #course;
DROP TABLE #Test;

答案 1 :(得分:0)

根据我的理解,您希望从整个表格中返回当天课程详细信息的最短日期。 请尝试以下脚本

SELECT TOP 1 MIN(t.testDate) OVER (ORDER BY t.testDate) AS TestDate ,
        t.courseId ,
        c.name
FROM    Test t 
        INNER JOIN course c ON t.courseId = c.id
ORDER BY t.testDate