我们说我的查询结果如下:
ContactID LeadSalePrice
---------------------------
45 19.90
45 18.00
32 17.50
但是,我希望消除重复的ContactID,始终采用更高的价格结果。所以我想要的是:
ContactID LeadSalePrice
---------------------------
45 19.90
32 17.50
这是查询的简化版本:
SELECT
sc.ContactID
, c.LeadSalePrice
FROM
LeadSalesCampaignCriterias c
JOIN LeadSalesCampaigns sc ON c.LeadSalesCampaignID = sc.LeadSalesCampaignID
WHERE
...
ORDER BY
LeadSalePrice DESC
我一直在玩DISTINCT和GROUP BY,但我没有得到它。
答案 0 :(得分:2)
只需使用GROUP BY
:
SELECT sc.ContactID, MAX(c.LeadSalePrice) as LeadSalePrice
FROM LeadSalesCampaignCriterias c JOIN
LeadSalesCampaigns sc
ON c.LeadSalesCampaignID = sc.LeadSalesCampaignID
WHERE ...
GROUP BY sc.ContactID;
答案 1 :(得分:1)
另一个选项是WITH TIES和Row_Number()
Select Top 1 with Ties *
From YourTable
Order By Row_Number() over (Partition By ContactID Order By LeadSalePrice Desc)
返回
ContactID LeadSalePrice
32 17.50
45 19.90