我们的客户向我们提供包含重复商品的合同。我们宣传独特的产品。如何在不进行多次子查询的情况下选择一组具有描述的不同upc?可怕的例子:
/*
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来创建记录或显示重复项?
答案 0 :(得分:5)
你可能会做这样的事情:
SELECT A.eventid, A.upc_ean, MAX(description) as description, MAX(size) as size
FROM myTable
GROUP BY eventid, upc_ean
你应该得到类似的结果。
答案 1 :(得分:5)
如有必要,您可以根据需要在下面的OVER部分添加ORDER BY子句。
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
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