涉及CTE、CASE和子查询的SQL Server查询
以下是我正在使用的数据集:涉及CTE、CASE和子查询的SQL Server查询,sql,sql-server,sql-server-2008,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',
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,如果任何子ID的corptype为“Y”,则选择masterID、subID、corptype和entrydate
2.)对于任何子ID都没有“Y”的masterID,我需要选择具有最新入口日期的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
如果我理解正确,这是一个奇怪的排序问题。这似乎很奇怪,因为优先级来自两个表。首先是来自
test2
的corptype,然后是来自test
的entrydate
您可以使用row\u number()
解决这类问题。如果我是对的,那么这可能会满足您的要求:
select t.masterId, t.smallId, t.corptype, t.entrydate
from (select t.masterID, t.smallID, t2.corptype, t.entrydate,
row_number() over (partition by t.masterId
order by (case when t2.corptype = 'Y' then 0 else 1 end),
t.entrydate desc
) as seqnum
from test t join
test2 t2
on t.smallid = t2.smallid
) t
where seqnum = 1;
您可以添加当前查询生成的输出吗?是smallid还是subid?为什么masterId=3在输出中得到E而不是C?另外,当表test2中的多条记录的samre masterID有一个Y inm it时,您想要什么?你只想要;test2中的一行或所有“y”行?@KevinPostlewaite:我收到以下错误:Msg 4104,级别16,状态1,第8行多部分标识符“test2.corptype”无法绑定。Msg 116,Level 16,State 1,Line 21当子查询没有引入EXISTS时,只能在选择列表中指定一个表达式。@VJHil:对不起,我的错误;所有smallID都应该是“subID”;我对原始表进行了更改,以便它们更容易理解,但我没有进行所有必要的更改。我正在编辑中修正这一点。嘿,戈登,我在原始帖子的插入部分犯了一个错误;您的查询返回正确!非常感谢。
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)