SQL SUM区别重复问题然后转换为linq

时间:2013-10-03 12:29:39

标签: sql linq

我有一个问题,我试图编码。

我需要点击小部件的价格总和,所以写了以下查询:

SELECT SUM(Price)
FROM
(select distinct (wc.id), rp.Price  from Widgetclicks wc
join RetailerProducts rp on wc.ProductId = rp.ProductId
join ManufacturerWidgets mw on wc.ManufacturerWidgetId = mw.Id
where rp.RetailerId = 7 and  mw.ManufacturerId = 41 and mw.Enabled = 1 and mw.CountryId = 230 and wc.CreatedAt >= '2013-09-01 00:00:00.000' and wc.CreatedAt <= '2013-09-30 23:59:59.000'

)as total

但是,由于零售商产品表中有重复数据,因此它将为该wc.Id的所有价格汇总。

例如,如果我自己运行以下查询:

select distinct (wc.id), rp.Price  from Widgetclicks wc
join RetailerProducts rp on wc.ProductId = rp.ProductId
join ManufacturerWidgets mw on wc.ManufacturerWidgetId = mw.Id
where rp.RetailerId = 7 and  mw.ManufacturerId = 41 and mw.Enabled = 1 and mw.CountryId = 230 and wc.CreatedAt >= '2013-09-01 00:00:00.000' and wc.CreatedAt <= '2013-09-30 23:59:59.000'

我会得到这样的结果:

Id          Price
20088492    179.99
20088501    179.99
20088905    299.99
20088905    309.94
20088915    299.99
20088915    309.94
20091364    249.99
20091364    279.99
20093608    449
20093608    468.95
20093615    449
20093615    468.95

在某些情况下,您可以看到有多个ID,即

 20088905   299.99
 20088905   309.94

我需要做的是,如果我想要获得第一个ID的ID有多个价格,那么当我总和不会加倍某些值时。我知道那里有两个价格,但我只想抓住第一个。

我还需要将其转换为Linq。

修改

感谢ChrisL,它让我考虑使用updatedDate以及以下查询:

select sum (Price) as price  from Widgetclicks wc
left join (select ProductId, MAX(UpdatedDate)As date 
from RetailerProducts 
Group By ProductId)
rp on wc.ProductId = rp.ProductId
join ManufacturerWidgets mw on wc.ManufacturerWidgetId = mw.Id
where RetailerId = 7 and  mw.ManufacturerId = 41 and mw.Enabled = 1 and mw.CountryId = 230 and wc.CreatedAt >= '2013-09-01 00:00:00.000' and wc.CreatedAt <= '2013-09-30 23:59:59.000'

我希望这是有道理的。

非常感谢

1 个答案:

答案 0 :(得分:0)

尝试使用此查询,它会将RetailerProduct连接限制为仅包含一个匹配的行与最新的“UpdateDate”

SELECT SUM(Price)
FROM
(select distinct (wc.id), rp.Price  from Widgetclicks wc
join RetailerProducts rp on wc.ProductId = rp.ProductId
and rp.id = (select top 1 id from retailerProducts where productid = wc.productid order by UpdateDate desc)
join ManufacturerWidgets mw on wc.ManufacturerWidgetId = mw.Id
where rp.RetailerId = 7 and  mw.ManufacturerId = 41 
and mw.Enabled = 1 and mw.CountryId = 230 and wc.CreatedAt >= '2013-09-01 00:00:00.000' 
and wc.CreatedAt <= '2013-09-30 23:59:59.000'
)as total

TOP 1语法假设MS sql server,在其他数据库LIMIT 1中使用相同的效果。

转换为LINQ时,读取此101 LINQ Samples