涉及CTE,CASE和子查询的SQL Server查询

时间:2014-06-05 18:51:38

标签: sql sql-server sql-server-2008

这些是我正在使用的数据集:

create table test (
masterid int, 
subID varchar(100),
entrydate datetime
)

insert into test
values 
(1,'A','5/1/14'),
(1,'B','4/1/14'),
(1,'C','3/1/14'),
(2,'D','4/1/14'),
(2,'E','6/1/14'),
(2,'F','2/1/14'),
(3,'A','12/1/13'),
(3,'B','1/1/14'),
(3,'E','2/1/14');


Create table test2 (
subID varchar(50),
corptype varchar(50)
)

insert into test2 
values
('A','N'),
('B','N'),
('C','Y'),
('D','Y'),
('E','N'),
('F','N')

    select t1.masterid
           , t1.subID 
           , t2.corptype
           , t1.entrydate
    from   test t1
           join test2 t2 on t1.subID = t2.subID 

我必须编写一个符合以下要求的查询:

1。)对于给定的masterID,如果任何subID的corptype是'Y',则选择masterID,subID,corptype和entrydate。

2.。)对于任何subID没有'Y'的masterID,我需要选择具有最新entrydate的masterID,subID,corptype和entrydate。

请假设masterID列表太长,无法首先识别所有Y,然后选择Y列表中没有masterID的N.

我的尝试:

    WITH cte AS
                (
                   SELECT *,
                         ROW_NUMBER() OVER (PARTITION BY t1.masterid ORDER BY t1.entrydate DESC) AS rn
                   FROM test t1
                )

    select CASE (test2.corptype)
    when 'Y'

    THEN

                (select t1.masterid
                        , t1.subID 
                        , t2.corptype
                        , t1.entrydate
                from test t1
                join test2 t2 on t1.subID = t2.subID 
                where t2.corptype = 'Y')

    ELSE            

                (SELECT cc.masterid, cc.subID, t2.corptype, cc.entrydate
                FROM cte cc
                join test2 t2 on cc.subID = t2.subID 
                WHERE rn = 1
                and t2.corptype = 'N'
                --order by cc.entrydate
                )

    END

最终输出应为:

masterid    subID corptype    entrydate
1           C      Y            00:00.0
2           D      Y            00:00.0
3           E      N            00:00.0

2 个答案:

答案 0 :(得分:0)

如果我理解正确,这是一种奇怪的优先级问题。这似乎很奇怪,因为优先事项来自两个表格。来自test2的第一个公告类型,然后来自entrydate的{​​{1}}。

您可以使用test解决此类问题。如果我是对的,那么这可能会做你想要的:

row_number()

答案 1 :(得分:0)

Select a.MasterId, coalesce(b.subId, c.subId),
   a.entrydate,  
From test a
   Left join test2 b 
      on b.subID = a.subID
         and b.corptype = 'Y'
  join test2 c 
      on c.subID = a.subID
         and a.entryDate =
             (Select Max(entryDate)
              from test 
              where MasterId = a.MasterId)