store item datekey onhand salesunits
--------------------------------------------
001 A 50 65 2
001 A 51 8 4
001 A 52 0 8
--------------------------------------------
達成するために必要なもの:ゼロより大きい最新の値を店舗やアイテムごとにマイナスします。したがって、上記の例では、8-14 = -6になります。T-SQL - 相関サブクエリからの集計を使用するすべての行の集計
相関サブクエリを使用して、最新の日付キーを決定してから、メインクエリに再び参加します。しかし、明らかにそうすることによって、私はsalesunitsを合計するために必要な他の行に関連するデータを失う:
これは私が持っているものであり、それは間違っている:あなたの助けを
select s1.Store, s1.Item, s1.OnHand, sum(salesunit)
from sales s1
join (select top 1 store,item, max(DateKey) as datekey
from sales
where isnull(onhand,0) > 0
and DateKey in (50,51,52)
group by store, item) s2 on s2.store=s1.store and s2.item=s1.item and s2.datekey=s1.datekey
group by s1.Store, s1.Item, s1.OnHand
ありがとう!
私の1だったがSIGNのために。いい感じです –