SQL Server:从输出的特定列中筛选出重复值

时间:2015-09-09 20:09:00

标签: sql-server duplicates

我正在使用SQL Server 2014,我有以下查询针对View Table运行:

USE MyDatabase
SELECT a.ResaId, a.MTH, a.Market, SUM(a.Guest) AS 'Pax'
FROM RESLIST a
GROUP BY a.ResaId, a.MTH, a.Market

输出(提取)如下:

ResaId      MTH     Market    Pax
  252     Jan-15    France     3
  346     FEB-15    UK         2
  346     MAR-15    UK         2
  112     MAR-15    GERMANY    4
  587     JUL-15    Italy      3
  587     AUG-15    Italy      3

我需要输出来排除那两个重复的ResaID:346和587.因此,输出需要如下:

ResaId      MTH     Market    Pax
  252     Jan-15    France     3
  346     FEB-15    UK         2
  112     MAR-15    GERMANY    4
  587     JUL-15    Italy      3

SELECT DISTINCT语法不起作用。我想这是因为整个ROWS中的值不是重复的。

我只需要消除具有重复ResaID的SECOND ROW。

如何将相关语法编写到现有查询中以实现此目的?

1 个答案:

答案 0 :(得分:2)

您可以使用{/ 3}}功能

SELECT 
    ResaId,
    MTH,
    Market,
    Pax
FROM 
    (SELECT 
         a.ResaId, a.MTH, a.Market, SUM(a.Guest) AS 'Pax',
         ROW_NUMBER() OVER(PARTITION BY a.ResaId ORDER BY a.ResaId) AS rn
     FROM 
         RESLIST a
     GROUP BY 
         a.ResaId, a.MTH, a.Market) xx
WHERE 
    rn = 1;