如何创建临时表或仅从循环中的列中选择不同的值
Posted
技术标签:
【中文标题】如何创建临时表或仅从循环中的列中选择不同的值【英文标题】:how to create a temporary table or to select only distinct values from a column in a loop 【发布时间】:2012-08-23 15:40:06 【问题描述】:我有一个有 2 列的表,第一列有重复值,现在在 while 循环中我想一次选择每个不同的值,我在 sql 中创建了一个临时表,但是在 oracle sql developer 中我该如何编写代码?
CREATE TABLE look_up_table
(row_id INT NOT NULL,
attribute VARCHAR(500),
VARCHAR(700)
)
/* now manually populating this table */
INSERT INTO look_up_table
VALUES
(1, grmacolor_frame_access, black);
(2, grmacolor_frame_access, blue);
(3, grmacolor_frame_access, red);
(4, grmamaterial_frame_access, acetate);
(5, grmamaterial_frame_access, metal);
(6, grmamaterial_frame_access, nylon);
(7, grmamaterial_frame_access, plastic);
DECLARE @temp_col_val NVARCHAR (700), @counter1 INT,
SET @counter1 = 0;
SET @column_count = (SELECT COUNT (DISTINCT attribute) FROM look_up_table);
CREATE TABLE #temp1 AS
SELECT DISTINCT attribute AS attrib,
ROW_NUMBER() OVER (ORDER BY attribute) AS seqno1,
FROM look_up_table;
WHILE (@counter1 < @column_count)
BEGIN;
SET @temp_col_val = (SELECT attrib FROM #temp1 WHERE seqno1 = @counter1;
请帮忙
【问题讨论】:
【参考方案1】:以下代码将遍历每个属性并打印出来:
declare
curField varchar2(100);
resultCnt number ;
begin
select count(distinct attribute) into resultCnt from look_up_table;
for ind in 1..resultCnt loop
select attribute into curField from (
select attribute, rownum rwn
from
(
select distinct attribute
from look_up_table
)
) where rwn = ind;
dbms_output.put_line (curField);
end loop;
end;
/
【讨论】:
以上是关于如何创建临时表或仅从循环中的列中选择不同的值的主要内容,如果未能解决你的问题,请参考以下文章