首页 文章

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

提问于
浏览
-1

我有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

    要获得行输出:

    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
    ) )
    
  • 0

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

    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`;
    

    如果要获取特定年份的结果,请使用 HAVING 子句 . 对于SQL使用DATEPART()函数 . 对于oracle使用EXTRACT() .

相关问题