如何获得SQL中的最后出售价格
问题描述:
我正在处理一个查询,该查询将显示基本物料信息以及已发货总量(对于所有订单),物料出售的最后日期以及它的价格在...处售卖。我不知道如何获得最后的售价。这是我到目前为止,如何获得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
任何帮助,将不胜感激。
答
如果我理解正确的话,你可以使用条件汇总:
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
年是数字。
编辑你的问题,并提供样本数据和预期结果。 –