使用分组依据删除重复项

时间:2014-05-03 01:06:53

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

我对此No duplicates in SQL query

有类似的问题

find here the sqlFiddle

我有这个:

+----------+-----------------+----------+----------+-----------+----------+
| TAFIELDA |   DESCRIPTION   | TBFIELDA | TBFIELDB | DOCNUMBER | TCFIELDB |
+----------+-----------------+----------+----------+-----------+----------+
|     1000 | some data       |     2000 |     1000 |       525 |     2000 |
|     1001 | some other data |     2000 |     1001 |       525 |     2000 |
+----------+-----------------+----------+----------+-----------+----------+

预期结果:

+----------+-----------------+----------+----------+-----------+----------+
| TAFIELDA |   DESCRIPTION   | TBFIELDA | TBFIELDB | DOCNUMBER | TCFIELDB |
+----------+-----------------+----------+----------+-----------+----------+
|     1001 | some other data |     2000 |     1001 |       525 |     2000 |
+----------+-----------------+----------+----------+-----------+----------+

我只需要TAFIELDA的最高DocNumber = 525值,所以我这样做了:

SELECT max(tAFieldA) tAFieldA,DocNumber
FROM TABLEA A
INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
where DocNumber = 525
group by (DocNumber)

该查询只返回我正在寻找的行,问题是如果我添加另一个无法摘要的字段,例如Description,我会再次获得几条记录。

¿我怎么能每DocNumber个{{1}}的所有字段只获得一条记录?

3 个答案:

答案 0 :(得分:1)

使用子查询

SELECT * FROM 
(
SELECT *
      ,ROW_NUMBER() OVER (PARTITION BY DOCNUMBER ORDER BY tAFieldA DESC) rn
FROM TABLEA A
INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
) Sub 
WHERE rn = 1

使用CTE

;WITH CTE
 AS
   (
    SELECT *
          ,ROW_NUMBER() OVER (PARTITION BY DOCNUMBER ORDER BY tAFieldA DESC) rn
    FROM TABLEA A
    INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
    INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
   )
 SELECT * FROM CTE
 WHERE rn = 1

Working SQL FIDDLE

答案 1 :(得分:0)

使用子查询:

SELECT *
FROM TABLEA A
INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
WHERE TAFIELDA IN (
  SELECT max(tAFieldA)
    FROM TABLEA A
   INNER JOIN TABLEB B ON A.TAFIELDA = B.TBFIELDB
   INNER JOIN TABLEC C ON B.tBFieldA = C.tCFieldB
   WHERE DocNumber = 525
   GROUP BY (DocNumber)
  )

答案 2 :(得分:0)

select a.* ,b.* ,c.* 
from tablea a
inner join tableb b on a.tafielda = b.tbfieldb
inner join tablec c on b.tbfielda = c.tcfieldb
where (tafielda,docnumber) in
    (
        select max(tafielda) tafielda,docnumber
        from tablea a
        inner join tableb b on a.tafielda = b.tbfieldb
        inner join tablec c on b.tbfielda = c.tcfieldb
        where docnumber = 525
        group by (docnumber)
    )