使用单个查询获取单个月的数据

时间:2017-05-11 08:57:58

标签: sql oracle

我有3个表格,如下图所示(我只提供样本数据,但实际表格中包含所有月份的数据)。我的SALES表将包含未来(未来出售)和过去日期的数据。

select  item_id as agg from item_category f JOIN 
sales t ON f.item_id=t.item_id where t.selling_date
BETWEEN sysdate AND sysdate+21 and f.item_type='medicine';

现在我的查询返回了未来21天内售出的ITEMS。现在我希望在过去的一年中获得这些项目的利润 例如,我希望最后一年的利润为1月:2000,feb:3000,mar:1000 ....... enter image description here

2 个答案:

答案 0 :(得分:0)

您可以按销售日期对项目进行分组并汇总此利润。

Map

如果您想获得特定年份的结果,请使用SELECT YEAR(sold_date) AS `Year`, MONTH(sold_date) AS `Month`, SUM(profit) AS Profit FROM sales JOIN Reventue_Table ON sales.item_id=Reventue_Table.item_id GROUP BY `Year`, `Month`; 子句。对于SQL使用DATEPART()函数。对于oracle使用EXTRACT()

答案 1 :(得分:0)

获取行中的输出:

SELECT -- s.item_id,                           -- Not sure if you want it total or per item
       TRUNC( s.sold_date, 'MM' ) AS sold_month,
       SUM( r.profit ) AS total_profit
FROM   sales s
       INNER JOIN
       revenue_table r
       ON ( s.item_id = r.item_id )
GROUP BY -- s.item_id,                         -- Not sure if you want it total or per item
       TRUNC( s.sold_date, 'MM' )

PIVOT行添加到列中:

SELECT *
FROM   (
  SELECT -- s.item_id,                         -- Not sure if you want it total or per item
         TRUNC( s.sold_date, 'MM' ) AS sold_month,
         r.profit
  FROM   sales s
         INNER JOIN
         revenue_table r
         ON ( s.item_id = r.item_id )
)
PIVOT ( SUM( profit ) FOR sold_month IN (
  DATE '2017-05-01' AS May2017,
  DATE '2017-04-01' AS Apr2017,
  DATE '2017-03-01' AS Mar2017,
  DATE '2017-02-01' AS Feb2017,
  DATE '2017-01-01' AS Jan2017,
  DATE '2016-12-01' AS Dec2016,
  DATE '2016-11-01' AS Nov2016,
  DATE '2016-10-01' AS Oct2016
) )