2

我不想在下面的 sql 的输出显示重复的行,所以我在那里有“不同”,但这不起作用。我得到如下输出:

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

4

5 回答 5

10

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
于 2013-01-08T16:20:37.160 回答
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
于 2013-01-08T16:18:56.570 回答
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
于 2013-01-08T16:19:11.607 回答
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

这将起作用,但没有创建日期

于 2013-01-08T16:19:21.593 回答
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])对每一行的所有值做一些事情,所以将它们组合在一起并显示每个的最小值。

于 2013-01-08T16:19:02.860 回答