0

コードラウンドを試みている問題があります。

ウィジェットのクリックが発生した価格の合計が必要なため、次のクエリを作成しました。

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 に複数の価格がある場合、最初の価格を取得して、合計すると一部の値が 2 倍にならないようにすることです。そこには 2 つの価格があることは知っていますが、最初の価格を取得したいだけです。

これを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'

それが理にかなっていることを願っています。

どうもありがとう

4

1 に答える 1

0

このクエリを使用してみてください。RetailerProduct 結合が制限され、最新の "UpdateDate" と一致する行が 1 つだけ含まれるようになります。

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 サンプルを読むことができます

于 2013-10-03T14:00:25.507 に答える