问题描述
我想要的以下数据输出应如下所示:
id empid question type rownum
1 75 How old are you SSS 1
2 75 NULL LLL 2
3 88 How old are you SSS 1
4 88 NULL LLL 2
5 99 How old are you SSS 1
6 99 How old are you LLL 1
7 99 NULL LLL 2
我想要的输出是,如果有一个同时具有SSS和LLL类型的Empid,但LLL问题为空,则仅返回SSS记录。在某些情况下,一个Empid既可以带有问题的SSS和LLL类型,又可以包含带有空问题的第二个LLL类型。最后,我只会带回rownum = 1的那些记录。
declare @t table(id int,empid int,question varchar(250),type char(3))
insert into @t values( 1,75,'How old are you','SSS'),(2,NULL,'LLL'),(3,88,(4,(5,99,(6,(7,'LLL')
我写了下面的查询,它很接近,但是我无法得到我想要的确切结果,因为它正在为empid = 99的两种'LLL'类型分配rownum = 2。
select *,rank()over(partition by empid order by type desc,case when question is not null and type = 'LLL' then 1 else 2 end desc) as rownum
from @t
解决方法
我想我明白了
select *,dense_rank()over(partition by empid,case when question is not null and type =
'LLL' then 1 else 2 end order by type desc
) as rownum
from @t