当值更改SQL时,获取跨时间的唯一记录

时间:2015-06-03 19:49:34

标签: sql sql-server distinct-values

仍然使用2008.我有以下两个表,并且需要能够在给定日期首次代码为d时拉出个人。很容易得到那些从未有过e的人,但是如果以前的话,我无法弄清楚如何将他们包括在第一次。我已经尝试使用with来生成所有es的列表,而不是将其与其他es匹配,但是在确定如何将其与其他查询联系起来方面却没有成功。

Table1                                            Table2
Person  date1  date2  date3  date4  date5  date6  Person  FirstServ
1         e             e      d      d      d      1         date1
2                e      e                    d      2         date2
3                              d      d      d      3         date4
4                              d      d             4         date4
5         e                    d      d      d      5         date1
6         e      e                    d      d      6         date1
7                e      e      d      d      d      7         date2
8                              d      d      d      8         date4
9                              d      d             9         date4
10                             d      d      d     10         date4

没有引入with子句的当前代码是(并且我知道我不一定是最有效的编码器:))

declare @myorder int
set @myorder = (select academicOrder from DimTermYear dt3 where termID='14/FA');

with myDual as (
select distinct ds.STTR_STUDENT, dt.academicOrder
    from dbo.DimStudentTerms ds 
        left join DimTermYear dt on dt.termID=ds.STTR_TERM 
    where ds.STTR_STU_CURRENT_TYPE = 'DE'
)


Select distinct sa.STC_PERSON_ID,ds2.STTR_STU_CURRENT_TYPE,dt2.academicOrder
    from StudentAcadCredFrom2000 sa
        left join dbo.DimStudentTerms ds2 on ds2.STTR_STUDENT=sa.STC_PERSON_ID
        left join DimTermYear dt2 on dt2.termID=ds2.STTR_TERM 
    where (sa.STC_CURRENT_STATUS in ('A','N') or (STC_CURRENT_STATUS='D' and STC_GRADE IS NOT NULL))
    and sa.STC_TERM='14/FA' and ds2.D04_FIRST_TERM_ENR='14/FA'
    and ds2.STTR_STU_CURRENT_TYPE='DS' and dt2.academicOrder=@myorder
order by sa.STC_PERSON_ID

1 个答案:

答案 0 :(得分:0)

如果您事先知道表1只有6个日期列(date1date6),那么您可以按如下方式使用一系列案例:

with temp as (
    select Person, firstDateOfD = (
        CASE WHEN date1 = 'd' THEN date1
        CASE WHEN date2 = 'd' THEN date2
        CASE WHEN date3 = 'd' THEN date3
        CASE WHEN date4 = 'd' THEN date4
        CASE WHEN date5 = 'd' THEN date5
        CASE WHEN date6 = 'd' THEN date6)
    from Table1
) 
-- create your lists as you need.
-- e.g. date1_list = select Person from temp where firstDateOfD = date1