我有两个输入表 input_table_1如下所示:
prod_id store id net_sales gender color
1 1 34 m blue
2 1 43 f green
3 2 12 f green
4 3 22 f blue
5 3 56 m black
6 3 4 f green
第二个表是look_up_table,它具有表1的列名及其值:
attribut value_1
gender m
gender f
color blue
color green
color black
. .
. .
. .
我已创建此代码,其中我运行嵌套循环并在temp变量中存储attribute和value_1的值。现在我想从input_table_1中选择net_sales的总和,其中列名存储在temp_atr_val中,单元格值为temp_val。 我正在尝试这样的东西,但它不适合我,temp_sales变量不会取任何值。请帮助我如何使用select语句选择属性的特定值的销售总和。
代码:
declare
temp_atr_val varchar2(400);
temp_val varchar2 (400);
temp_name varchar2 (400);
temp_sum_percent decimal (10,3);
temp_variable number := 786;
column_count number ;
val_count number;
temp_storeid number (38,0);
temp_sales number ;
store_count number;
/* sales_store number; */
BEGIN
create table store_table as
select distinct id_dmstore
from input_table_1
order by store_id;
select count(distinct attribute) into column_count from look_up_table;
for ind in 1..column_count loop
/* putting current value of attribute from look_up_table in temp variable*/
select attribute into temp_atr_val from (
select attribute, rownum rwn
from
(
select distinct attribute
from look_up_table
order by attribute
)
) where rwn = ind;
select count( value ) into val_count from look_up_table
where ATTRIBUTE = temp_atr_val;
for ind in 1..val_count loop
/* putting current value_for_atr for corresponding attribute from look_up_table in temp variable*/
select value_for_atr into temp_val from
(
select value_for_atr, rownum rwn
from look_up_table
where ATTRIBUTE = temp_atr_val
) where rwn = ind;
select name_of_col into temp_name from
(
select name_of_col, rownum rwn
from look_up_table
where ATTRIBUTE = temp_atr_val
/* and VALUE_FOR_ATR = temp_val*/
) where rwn = ind;
select count (STORE_id )into store_count from store_table;
for ind in 1..column_count loop
select store_id into temp_storeid from (
select id_dmstore, rownum rwn
from store_table
order by store_id
)
where rwn = ind;
select sum(net_sales_home) into temp_sales
from input_table_1
where temp_atr_val = temp_val
and store_id = temp_storeid;
dbms_output.put_line (temp_sales);
end loop;
/* SELECT SUM(CASE WHEN temp_atr_val = temp_val THEN net_sales_home ELSE 0 END) into temp_variable
FROM schemafinal_1;
dbms_output.put_line (temp_val);
*/
/*temp_variable := temp_variable/sales_store; */
EXECUTE IMMEDIATE 'ALTER TABLE SAR ADD ('||temp_name||' number)';
EXECUTE IMMEDIATE ' UPDATE SAR b
SET b.'||temp_name||' = :temp_variable' using temp_variable;
END LOOP;
END LOOP;
END;
答案 0 :(得分:0)
如果您正在尝试创建一个新列来存储数据,并且看到每次在temp变量中出现新值时都会创建一个新列,为什么不尝试这样: 创建两个新列,并将其命名为column_name和column value。这样,您可以存储列的名称以及将存储在其中的值 稍后,要从该列中进行选择,而不是执行:
select column_name from table;
你会这样做:
select column_value from table where column_name = temp_variable;
如果我明白你想要做什么,当然......