我们的客户向我们提供重复项目的契约(Contract)。我们宣传独特的产品。如何在不进行许多子查询的情况下选择一组带有描述的不同 upcs?可怕的例子:
/*
eventID int
groupID int // This field is different between fields
upc_ean numeric(18,0)
description varchar(512) // Description is slightly different but same info
size varchar(512) // Size is slightly different but same info
*/
select A.eventid, A.upc_ean,
( select top 1 description
from myTable B
where B.eventid = A.eventid and B.upc_ean = A.upc_ean) as description,
( select top 1 size
from myTable B
where B.eventid = A.eventid and B.upc_ean = A.upc_ean) as size
from ( select distinct eventid, upc_ean from myTable) A
有没有办法在没有子查询的情况下做同样的事情,以某种方式将两者结合在一起,不会产生记录或使用 eventid 和 upc_ean 作为 PK 显示重复项?
最佳答案
如有必要,您可以在以下的 OVER 部分中添加 ORDER BY 子句。
使用 CTE:
WITH example AS (
SELECT a.eventid,
a.upc_ean,
a.description,
a.size,
ROW_NUMBER() OVER(PARTITION BY a.eventi, a.upc_ean) AS rank
FROM YOUR_TABLE a)
SELECT x.eventid,
x.upc_ean,
x.description,
x.size
FROM example x
WHERE x.rank = 1
没有 CTE:
SELECT x.eventid,
x.upc_ean,
x.description,
x.size
FROM (SELECT a.eventid,
a.upc_ean,
a.description,
a.size,
ROW_NUMBER() OVER(PARTITION BY a.eventi, a.upc_ean) AS rank
FROM YOUR_TABLE a) x
WHERE x.rank = 1
关于SQL:如何选择具有重复项的唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4181187/