我有一个问题,我正在尝试编写代码。
我需要小部件点击发生的价格总和,因此编写了以下查询:
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 有多个价格,我想获得第一个价格,这样当我求和时不会在某些值上加倍。我知道那里有两个价格,但我只想抢第一个。
我还需要将其转换为 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'
我希望这是有道理的。
非常感谢