2017-10-17 61 views
0

我正在處理一個查詢,該查詢將顯示基本物料信息以及已發貨總量(對於所有訂單),物料出售的最後日期以及它的價格在...處售賣。我不知道如何獲得最後的售價。這是我到目前爲止,如何獲得SQL中的最後出售價格

SELECT 
    item_id 
    ,item_desc 
    ,sum(qty_shipped) AS 'Total Qty Shipped' 
    ,count(item_id) AS 'No of times Shipped' 
    ,max(invoice_date) AS 'Last Invoice_date' 
    ,unit_price AS 'Last Price' 
FROM sales_history_report 
WHERE 
    item_id = '1234' 
    AND year_for_period >= '2017' 
    AND sales_location_id like '10' 
GROUP BY 
    item_id 
    ,item_desc 
    ,unit_price 

與此查詢我收到此項目的所有行。它看起來像現在這種權利,

ITEM_ID,ITEM_DESC,Total_QTY_shipped,no_of_times_shipped,Last_Invoice_date,Last_price
1234,項目1234,4,1,2014-10-15,2.47
1234,項目1234,6,1 ,2014-09-20,2.519

但是我正在尋找 ITEM_ID,ITEM_DESC,Total_QTY_shipped,no_of_times_shipped,Last_Invoice_date,Last_price
1234,項目1234,10,2,2014-10-15,2.47

任何幫助,將不勝感激。

+0

編輯你的問題,並提供樣本數據和預期結果。 –

回答

1

如果我理解正確的話,你可以使用條件彙總:

select item_id, item_desc, 
     sum(qty_shipped) as [Total Qty Shipped], 
     count(item_id) as [No of times Shipped], 
     max(invoice_date) as Max_Date, 
     max(case when seqnum = 1 then unit_price end) as [Last Price], 
from (select shr.*, 
      row_number() over (partition by item_id order by invoice_date desc) as seqnum 
     from sales_history_report shr 
    ) shr 
where item_id = 1234 and 
     year_for_period >= 2017 and 
     sales_location_id like '10' 
group by item_id, item_desc; 

評論:

  • 不要爲列別名使用單引號。只對字符串和日期常量使用單引號。
  • GROUP BY中的列定義結果集中的行。我認爲你不需要unit_price
  • 請勿爲數字常量使用單引號。我假設item_id年是數字。