我有表psc_Pro_ProfessorPositions(ProfessorID,PositionID,StartDate,EndDate)。它有2个主键是ProfessorID,PositionID。
我想检查一下ProfessorID,我不想在表格中插入PositionID。我写的是这样的:
插入CoreUIs.dbo.psc_Pro_ProfessorPositions ( ProfessorID,PositionID,开始日期,结束日期 )
select a.MaQuanLy,b.MaQuanLy,convert(smalldatetime,NgayHieuLuc),convert(smalldatetime,NgayHetHieuLuc)
from inserted
inner join GiangVien a on a.MaGiangVien = inserted.MaGiangVien
inner join ChucVu b on b.MaChucVu = inserted.MaChucVu
where a.MaQuanLy not in (select ProfessorID from CoreUIs.dbo.psc_Pro_ProfessorPositions)
and b.MaQuanLy not in (select PositionID from CoreUIs.dbo.psc_Pro_ProfessorPositions)
但这是错的。可以帮帮我吗?谢谢大家。
答案 0 :(得分:1)
;WITH x AS
(
SELECT TeacherID, ClassID, ClassStuID, s = [SUM],
rn = ROW_NUMBER() OVER (PARTITION BY TeacherID ORDER BY ClassID)
FROM dbo.TB1
)
SELECT TeacherID, ClassID, ClassStuID,
[SUM] = CASE rn WHEN 1 THEN s ELSE NULL END
FROM x
ORDER BY TeacherID, [SUM] DESC;
答案 1 :(得分:0)
您可以使用带有ROW_NUMBER()OVER()的CTE来识别每个TeacherID的第一行:
; with a as (
select * from TB1
union
select * from TB2
)
, b as (
select *, r=ROW_NUMBER()over(partition by a.TeacherID order by a.TeacherID,
a.ClassID, a.ClassStuID) from a
)
select b.TeacherID, b.ClassID, b.ClassStuID
, [SUM]=case b.r when 1 then b.[SUM] else null end
from b
order by b.TeacherID, b.r
go
结果: