2013-10-03 26 views
0

我有我米試圖代碼一輪的問題。SQL SUM鮮明的重複問題,然後轉換爲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我想獲得第一個所以,當我總結一些價值不倍。我知道那裏有兩個價格,但我只想抓住第一個價格。

我將阿洛斯需要將其轉換到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' 

我希望是有道理的。

非常感謝

+0

讀你如何定義「第一」一個在選擇價格使用的條款? –

+0

@ChrisL如果我選擇*而不僅僅是選擇wc.Id和rp.Price的retailerProduct表確實有一個UpdatedDate列,所以如果我可以,我想使用最新UpdatedDate – anna

+0

好吧,我已經添加了一個答案。另外檢查鏈接瞭解有關轉換爲LINQ的一些指針。 –

回答

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服務器,在其他數據庫LIMIT 1用於相同的效果。

至於轉換爲LINQ有此101 LINQ Samples