Google
Information Storage and Retrieval: Write Your Number (SQL Puzzle 7)

Pages

Monday, July 7, 2008

Write Your Number (SQL Puzzle 7)

Problem: There are few sets of digits. Each set contains exactly ten digits - 0 to 9. You are given a number. Write an SQL logic to return the number of sets to write the given number. Note that 6 can be used as 9 and 9 can be used as 6.
e.g if the given number is 1234 , the answer will be 1 since we require 1 set to select each digit.
if the given number is 4444, the answer will be 4 since we require 4 sets to select each digit.
if the given number is 255, the answer will be 2.
if the given number is 6666, the answer will be 2 (Each set contains one 6 and one 9 and hence 2 sets are enough).

Solution:
select count(rn)
from
(
select distinct row_number() over (partition by room_no2 order by room_no2) rn from
(
select (case when room_no=9 and mod(rn,2)=0 then '6' else room_no end) room_no2
from
(
select substr(&room_no,rownum,1) room_no,row_number() over (partition by substr(&room_no,rownum,1) order by substr(&room_no,rownum,1)) rn
from all_objects
where
rownum<=length(&room_no)
)
)
)

No comments: