如何在SQL中获得最后的售价

时间:2017-10-17 01:33:18

标签: sql sql-server sql-server-2008

我正在处理一个查询,它会显示基本商品信息以及发货的总数量(所有订单),商品的最后销售日期和销售价格。我无法弄清楚如何获得最后的售价。这是我到目前为止所做的,

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

任何帮助都将不胜感激。

1 个答案:

答案 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年份是数字。