SQL:不显示重复项

时间:2013-01-08 16:15:02

标签: sql sql-server

我想在输出中为下面的sql显示重复的行,所以我有'distinct',但这不起作用。我输出如下:

PermitNumber PermitName CreatedOn  
111          ABCD       1/2/2011  
111          ABCD       3/4/2012  
222          DFES       3/6/2000  

我想只有一行111,但我得到的行超过1行,因为111有多个修改,但我不在乎它是否有1或1000。

select  distinct (dbo.PermitNumber(mp.PermitId)), 
        dbo.PermitName(mp.PermitId),
    mod.[CreatedOn] as [CreatedOn]
from    tblPermit mp, dbo.[tblModification] mod
where mod.PermitId = mp.PermitId
order by 1

使用SQL Server

5 个答案:

答案 0 :(得分:8)

Distinct适用于所有列,因此您可以使用聚合函数:

  select  mp.PermitNumber,
    mp.PermitName,
    max(mod.[CreatedOn])as [CreatedOn]
  from    tblPermit mp
  Inner join dbo.[tblModification] mod
      on mod.PermitId = mp.PermitId
  Group by mp.PermitNumber,
    mp.PermitName
  order by 1

答案 1 :(得分:2)

使用GROUP BY(具体语法取决于您的dbms):

select  (dbo.PermitNumber(mp.PermitId)), 
    dbo.PermitName(mp.PermitId),
min(mod.[CreatedOn] as [CreatedOn])
from    tblPermit mp, dbo.[tblModification] mod
where mod.PermitId = mp.PermitId
group by (dbo.PermitNumber(mp.PermitId)), dbo.PermitName(mp.PermitId)
order by 1

答案 2 :(得分:2)

;WITH latestRecord
AS
(
    SELECT  PermitNumber, PermitName, CreatedOn,
            ROW_NUMBER() OVER (PARTITION BY PermitNumber, PermitName
                                ORDER BY CreatedOn DESC) rn
    FROM    tblPermit
)
SELECT PermitNumber, PermitName, CreatedOn
FROM    latestRecord
WHERE   rn = 1

答案 3 :(得分:2)

您应该决定如何处理创建日期。例如,显示这些天的最大值。 Distinct应用于select子句中的所有字段。

select  distinct (dbo.PermitNumber(mp.PermitId)), 
        dbo.PermitName(mp.PermitId)
from    tblPermit mp, dbo.[tblModification] mod
where mod.PermitId = mp.PermitId
order by 1

这将有效,但没有创建日期

答案 4 :(得分:1)

根据问题中的有限信息尝试:

select  distinct (dbo.PermitNumber(mp.PermitId)), 
        dbo.PermitName(mp.PermitId),
    MIN(mod.[CreatedOn]) as [CreatedOn]
  --^^^new
from    tblPermit mp, dbo.[tblModification] mod
where mod.PermitId = mp.PermitId
group by (dbo.PermitNumber(mp.PermitId)), ---<<new
        dbo.PermitName(mp.PermitId),      ---<<new
order by 1

您需要对每行的所有mod.[CreatedOn])值执行某些操作,因此请将它们组合在一起并显示每个值的MIN。