问题
Suppose if Item-A's Sale in 2013 is 100 Quantity and I'm expecting 10% of sales growth in next year i.e. in 2014
--------------------
ITEM | YEAR | QTY |
--------------------
ITM-A| 2013 | 100 |
ITM-B| 2013 | 200 |
--------------------
if I want to forecast sale data for up to year 2015
------------------------------
Item | 2013 | 2014 | 2015 |
------------------------------
Item-A | 100 | 110 | 121 |--each year qty incremented by 10% of its
Item-B | 200 | 220 | 242 |--previous year qty
------------------------------
回答1:
try this,you have to use dynamic sql
Declare @toyear int=2016
Declare @forcast int=10
Declare @t table (ITEM varchar(50), years int, qty int)
insert into @t
select 'TM-A' ITEM , 2013 years, 100 qty
union all
select 'TM-B' ITEM , 2013 years, 200 qty
;with CTE1 as
(
select * from @t
union all
select b.ITEM,b.years+1,b.qty+((@forcast*b.qty)/100) from @t a
inner join cte1 b on a.ITEM=b.ITEM
and b.years<@toyear
)
select * from
(select * from cte1 )t4
pivot(min(qty) for years in([2013],[2014],[2015],[2016]))pvt
回答2:
Try this:
select item,
qty as '2013',
round(qty*1.1) as '2014',
round(qty*1.21) as '2015'
from sale;
A dynamic query using stored procedure
DELIMITER $$
create procedure p (IN end INT(10))
BEGIN
declare start int;
declare fact FLOAT;
SET fact = 1.1;
SELECT year into start FROM sale limit 1;
SET @QUERY1 = CONCAT("SELECT ITEM, QTY AS '",start,"'");
WHILE start < end DO
SET start = start + 1;
SET @QUERY1 = CONCAT(@QUERY1," ,qty*",fact," as '", start,"'");
SET fact = fact *1.1;
END WHILE;
SET @QUERY1 = CONCAT(@QUERY1," from sale");
PREPARE stmt FROM @QUERY1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
Output:
mysql> call p(2016);
+-------+------+-------+--------+---------+
| ITEM | 2013 | 2014 | 2015 | 2016 |
+-------+------+-------+--------+---------+
| itemA | 100 | 110.0 | 121.00 | 133.100 |
| itemB | 200 | 220.0 | 242.00 | 266.200 |
+-------+------+-------+--------+---------+
2 rows in set (0.00 sec)
回答3:
Check this question:
Pass a function return to another in the same row
Your function is simply the multiplication by 1.1
来源:https://stackoverflow.com/questions/22198973/how-do-i-can-show-forecast-years-data-from-row-into-column