如何在PL / SQL Oracle中获取每年日期范围的数字总和

时间:2018-08-07 23:24:20

标签: sql oracle

我有一个查询。我想获取像2010、2011、2012、2013这样的每年的数量总和。它适用于
a.sale_date between '01-JAN-2010' and '31-DEC-2010'

但不适用于
a.sale_date between '01-JAN-2010' and '31-DEC-2018'

  SELECT c.tnama, SUM (a.net_weight)
    FROM sales a,
         invoice b,
         buy c,
         estate d
   WHERE     a.sale_date BETWEEN '01-JAN-2010' AND '31-DEC-2018'
         AND b.estate_code = d.estate_code
         AND d.estate_code = '023'
         AND b.actual_sale_year = a.sale_year
         AND b.actual_sale_no = a.sale_no
         AND b.lot_no = a.lot_no
         AND c.t$cuno = a.buyer_code
GROUP BY c.tnama
ORDER BY 1, 2 DESC

2 个答案:

答案 0 :(得分:1)

  

获取每年的数量总和

意味着您实际上应该从SALE_DATE列中选择这一年,并将其包括在GROUP BY子句中。

虽然与您的问题无关,但您应该在DATE子句中使用WHERE数据类型值,例如

  • 日期文字,例如date '2018-12-31”或
  • TO_DATE函数,例如to_date('31.12.2018', 'dd.mm.yyyy')
  • 但不是字符串,例如'01-JAN-2010'

  SELECT c.tnama, 
         EXTRACT (YEAR FROM a.sale_date) c_year,    --> this 
         SUM (a.net_weight)
    FROM sales a,
         invoice b,
         buy c,
         estate d
   WHERE     a.sale_date BETWEEN DATE '2010-01-01'  --> use dates, not strings 
                             AND DATE '2018-12-31'
         AND b.estate_code = d.estate_code
         AND d.estate_code = '023'
         AND b.actual_sale_year = a.sale_year
         AND b.actual_sale_no = a.sale_no
         AND b.lot_no = a.lot_no
         AND c.t$cuno = a.buyer_code
GROUP BY c.tnama, 
         EXTRACT (YEAR FROM a.sale_date)            --> has to be included into the GROUP BY clause
ORDER BY 1, 2 DESC

答案 1 :(得分:0)

如果要在单独的栏中输入年份,请使用PIVOT。

我已使用虚拟数据进行演示,请根据您的要求进行更改。

WITH t
     AS (SELECT sales_value, TO_CHAR (sale_date, 'YYYY') sale_date
           FROM pivot_tab)
SELECT *
  FROM t PIVOT (SUM (sales_value) FOR sale_date IN ('2015', '2016')) yr

结果

╔══════╦═══════╗
║ 2015 ║ 2016  ║
╠══════╬═══════╣
║ 6000 ║ 10000 ║
╚══════╩═══════╝

SQL Fiddle Demo