我有一个列(COLUMN3)在某些情况下出现故障。我需要保留COLUMN1订单,然后显示新列“NUM_ITEM”的正确顺序。我不知道该怎么做。 我试过了:
SELECT CODIMP,COLUMN1,COLUMN2,COLUMN3,
SUM(CASE WHEN COLUMN2 = ('C170') THEN 1
ELSE 0 END) OVER (PARTITION BY COLUMN2 ORDER BY TO_NUMBER(COLUMN1)) NUM_ITEM
FROM SPED_DATA
WHERE CODIMP = 81 AND COLUMN2 IN ('C100','C170')
GROUP BY CODIMP,COLUMN1,COLUMN2,COLUMN3
ORDER BY TO_NUMBER(COLUMN1);
结果如下:
CODIMP COLUMN1 COLUMN2 COLUMN3 NUM_ITEM EXPECTED
81 2741 C100 0 0 0
81 2742 C170 4 1 1
81 2743 C170 2 2 2
81 2744 C170 1 3 3
81 2745 C170 3 4 4
81 2746 C100 0 0 0
81 2747 C170 2 5 1
81 2748 C170 1 6 2
81 2749 C100 0 0 0
81 2750 C170 1 7 1
81 2751 C100 0 0 0
81 2752 C170 1 8 1
“EXPECTED”列是我需要查看“NUM_ITEM”列的方式。
谢谢!
答案 0 :(得分:0)
使用行数差异方法,您可以对组进行分类,然后对连续的行使用row_number
。
select CODIMP,COLUMN1,COLUMN2,COLUMN3
,case when column2=170 then row_number() over(partition by codimp,column2,grp order by to_number(column1))
else 0 end as num_item
from (
SELECT CODIMP,COLUMN1,COLUMN2,COLUMN3,
ROW_NUMBER() OVER (PARTITION BY CODIMP ORDER BY TO_NUMBER(COLUMN1))
-ROW_NUMBER() OVER (PARTITION BY CODIMP,COLUMN2 ORDER BY TO_NUMBER(COLUMN1)) NUM_ITEM as grp
FROM SPED_DATA
WHERE CODIMP = 81 AND COLUMN2 IN ('C100','C170')
) t
答案 1 :(得分:0)
看起来您需要将值分成组,其中第2列为100.您可以使用累计总和来执行此操作。然后,在此之后,使用row_number()
:
select sd.*,
row_number() over (partition by grp order by column1) as expected
from (select sd.*,
sum(case when column2 = 'C100' then 1 else 0 end) over (order by column1) as grp
from sped_data sd
where column2 in ('C100', 'C170') and codimp = 81
) sd;
我不确定您是否确实需要订购结果。似乎order by column1
足以满足结果集。