我的table1像这样
Dept Class Dept1 Class1 date
NULL NULL a history 02-2020
NULL NULL a bio 02-2020
a math NULL NULL 02-2020
a chemi NULL NULL 02-2020
a history NULL NULL 02-2020
b PE NULL NULL 03-2020
b Music NULL NULL 03-2020
b Sport NULL NULL 03-2020
NULL NULL b Cook 03-2020
c Psy NULL NULL 04-2020
我们可以查询如下内容吗?>
Dept Class Dept1 Class1 date a math a history 02-2020 a chemi a bio 02-2020 a history NULL NULL 02-2020 NULL NULL NULL NULL 02-2020 NULL NULL NULL NULL 02-2020 b PE b Cook 03-2020 b Music NULL NULL 03-2020 b Sport NULL NULL 03-2020 NULL NULL NULL NULL 03-2020 c Psy NULL NULL 04-2020
目标尝试按部门,部门1和日期获取记录分组您可以将任何字段与nvarchar或interger一起使用我的查询并不正常
select coalesce(sm.dept, su.dept1) as dept,
sm.class,
su.class1,
sm.date
from
(select distinct w.*,
row_number() over (partition by dept order by [date] asc) as seqnum
from table1 w
) sm
full join
(select w.*,
row_number() over (partition by dept1 order by [date] asc) as seqnum
from table1 w
) su
on sm.dept = su.dept1 and sm.seqnum = su.seqnum
[我的table1像这样的部门类Dept1 Class1 date NULL NULL a history 02-2020 NULL NULL a bio 02-2020 a math NULL NULL 02-2020 a ...
是。 。 。您似乎希望按日期对齐“组”中的列。这是一种方法:
我知道您想按日期排序,然后按dept,class,dept1,class1列排序。在SQL Server中,默认情况下,NULL出现在顶部。因此,我将ZZZZZ替换为NULL值以使它们最终出现。您可以将ZZZZZ替换为大的varchar字段,该字段不会出现在您的dept,class,dept1,class1字段中。