0

I'm using oracle SQL, and i have the following query:

select replace(replace('count(distinct <thiscol>) over (partition by <nextcol>) / count(*) over () as <thiscol>_<nextcol>,',
                       '<thiscol>', column_name
                      ), '<nextcol>', lead(column_name) over (order by column_id)
              )
from all_tab_columns atc
where table_name = 'mytable'

The output supposed to be queries such as follow:

select id,
       count(distinct name2) over (partition by name3) / count(*) over (),
       count(distinct name3) over (partition by name4) / count(*) over (),
       . . .
from mytable;

I'm expecting to get instead of:

count(distinct name2) over (partition by name3) / count(*) over ()

this query:

count(distinct name3) over (partition by name2) / count(*) over ()

Anyone can advise how to replace the order of the column values? (<thiscol> and <nextcol>). I tried to replace <thiscol> with <nextcol> but it gave me the same result. I tried many other things with of success.

Anyone?

4
  • 1
    What output do you get and how that differs from what you want? Please also add an explanation in human language, not SQL, of what you are trying to achieve. Commented Dec 3, 2014 at 15:37
  • Done. Hope it's clear enough. Commented Dec 3, 2014 at 15:42
  • Then may be you need to use LAG instead of LEAD? Commented Dec 3, 2014 at 15:46
  • Only the value inside over() has changed. The other one didn't. Commented Dec 3, 2014 at 16:08

1 Answer 1

1

That is really strange. Instead, let's sort in the reverse order:

select replace(replace('count(distinct <thiscol>) over (partition by <nextcol>) / count(*) over () as <thiscol>_<nextcol>,',
                       '<thiscol>', column_name
                      ), '<nextcol>', lead(column_name) over (order by column_id desc)
              )
from all_tab_columns atc
where table_name = 'mytable';

Note the desc in the sort.

Sign up to request clarification or add additional context in comments.

1 Comment

@GordonLinoff..You are AMAZING! Thank you so much! I learned a lot from you. Many thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.