我有一个查询。我想获取像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
答案 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 ║
╚══════╩═══════╝