【问题标题】:SQL : select data with null value on end date if other record has the same start dateSQL:如果其他记录具有相同的开始日期,则在结束日期选择具有空值的数据
【发布时间】:2017-12-18 05:16:14
【问题描述】:

我目前正在使用 SQL Server 2008。我有多个记录让学生注册了同一门课程,但有些记录具有相同的开始日期和空值或结束日期的实际日期。如果同一学生的开始日期相同,我正在尝试获取具有空值的记录。系统中的数据还包含具有开始和结束日期的记录,但我打算保留这些记录。我已经尝试了下面的查询,但它没有给我任何结果。有没有办法做到这一点?任何帮助,将不胜感激。

SELECT DISTINCT
  t1.*
FROM Enrolled_students t1
JOIN Enrolled_students t2
  ON t1.studentid = t2.studentid
  AND t1.program_enrolled = t2.program_enrolled
  AND t1.startdate = t2.stardate
  AND t1.enddate <> t2.enddate

数据

StudentID    program    StartDate            enddate_Date
267342      Science   2016-09-19 00:00:00.000    NULL
267342      science   2016-09-19 00:00:00.000   2017-01-17 00:00:00.000 
435359      math      2017-05-18 00:00:00.000   2017-08-29 00:00:00.000
290332      Lab       2014-02-11 00:00:00.000   NULL 

结果

StudentID    program    startDate            end_Date
267342      Science   2016-09-19 00:00:00.000    NULL
435359      math      2017-05-18 00:00:00.000   2017-08-29 00:00:00.000
290332      Lab       2014-02-11 00:00:00.000   NULL 

【问题讨论】:

  • 转述;您想删除任何具有NULL 结束日期的记录,但前提是存在匹配的记录(相同的学生、课程和开始日期),该记录具有实际的(NOT NULL) i> 结束日期?

标签: sql sql-server-2008 tsql


【解决方案1】:

运行以下 SQL。这将返回带有结束日期的学生记录,该记录在同一个表中有另一个条目,用于相同的学生+课程+开始日期组合,结束日期为 NULL

SELECT
*
FROM Enrolled_students 
    WHERE enddate_Date IS NOT NULL
        AND EXISTS
        (
            SELECT
                1
                FROM Enrolled_students  ES
                    WHERE ES.StudentID = Enrolled_students.StudentID
                        AND ES.Program = Enrolled_students.Program
                        AND ES.StartDate = Enrolled_students.StartDate
                        AND ES.enddate_Date IS NULL
        )

【讨论】:

  • 我认为这是从后到前的...... OP说I am trying to get the records with the null value
  • 有时你会收到一条消息说“空值被设置操作消除”
【解决方案2】:

你可以试试这个。

SELECT * FROM Enrolled_students E1
WHERE NOT EXISTS
    ( SELECT * FROM Enrolled_students E2 
        WHERE E1.StudentID = E2.StudentID
            AND E1.enddate_Date IS NOT NULL 
            AND E2.enddate_Date IS NULL )

结果:

StudentID   program              StartDate               enddate_Date
----------- -------------------- ----------------------- -----------------------
267342      Science              2016-09-19 00:00:00.000 NULL
435359      math                 2017-05-18 00:00:00.000 2017-08-29 00:00:00.000
290332      Lab                  2014-02-11 00:00:00.000 NULL

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多