选择查询连接选择TOP 1

时间:2016-11-04 03:30:11

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

我在这里有三张表:DinasHoHeaderDinasHoDetailEmployee

首先我有这个查询

select a.KodeDinasHeader,c.Nip,DepartmentCode 
from DinasHoHeader a 
left join DinasHoDetail b on a.KodeDinasHeader = b.KodeDinasHeader 
left join employee c on b.Nip = c.Nip
where DepartmentCode = 'IT'

我得到了这个结果

KodeDinasHeader   Nip        DepartmentCode
DN0000007       1501971           IT
DN0000007       1411517           IT

正如您所见,我得到重复KodeDinasHeader。我知道这是因为我有不同的Nip。因为我只想展示KodeDinasHeaderDepartmentCode。我正在尝试将查询更改为此

SELECT a.KodeDinasHeader,DepartmentCode From DinasHoHeader a 
left join (
select TOP 1 * from DinasHoDetail
) b on a.KodeDinasHeader = b.KodeDinasHeader
left join employee c on b.Nip = c.Nip
where c.DepartmentCode = 'IT'

我得到空的结果。我怎样才能做到这一点?

KodeDinasHeader     DepartmentCode
    DN0000007            IT

3 个答案:

答案 0 :(得分:4)

试试这个:

select DISTINCT a.KodeDinasHeader,DepartmentCode 
from DinasHoHeader a 
left join DinasHoDetail b on a.KodeDinasHeader = b.KodeDinasHeader 
left join employee c on b.Nip = c.Nip
where DepartmentCode = 'IT'

注意,我已经添加了DISTINCT并从选择列表中删除了Nip列。

答案 1 :(得分:1)

当你不需要压区时,为什么要加入桌面员工呢? Nothnig表明Dept代码属于哪个表。

这个怎么样,

declare @DeptCode varchar(50)='IT'
select a.KodeDinasHeader,@DeptCode DepartmentCode 
from DinasHoHeader a 
left join DinasHoDetail b on a.KodeDinasHeader = b.KodeDinasHeader -- or inner join
where DepartmentCode = @DeptCode

答案 2 :(得分:0)

像这样重写您的查询。请注意,我添加了TOP 1,因此您无需删除任何列。但如果你不需要" Nip"您可以删除此列

select TOP 1 a.KodeDinasHeader,c.Nip,DepartmentCode 
from DinasHoHeader a 
left join DinasHoDetail b on a.KodeDinasHeader = b.KodeDinasHeader 
left join employee c on b.Nip = c.Nip
where DepartmentCode = 'IT