Getting count of occurances of a string in a column value

Hi,
Is there a way to get the number of occurences of a string in a single column value?
Example:
CREATE TABLE STRING_CNT(X VARCHAR2(100));
INSERT INTO STRING_CNT(X) VALUES('OracleXXOracleXXOracleXXOracle');
Commit;
Now the string 'Oracle' is repeated 4 times in the inserted value. I would like to get this count using SQL.Can some one tell me how to get this?
I was asked this interesting question in an interview today.

hi<br>
u can get the occurrence of a string in text as
follow<br>
>
SELECT (LENGTH(x)-LENGTH(REPLACE(x,'Oracle', ' ' )))<br>
/ LENGTH('Oracle') as<br>
Occurrence FROM STRING_CNT;<br><br>
<br>
Are you sure...?<br>
<br>
<br>
SQL> with STRING_CNT as
  2  (select '1.Oracle2.Oracle3.' x
  3  from dual)
  4  SELECT (LENGTH(x)-LENGTH(REPLACE(x,'Oracle', ' ' ))) / LENGTH('Oracle') as Occurrence
  5  FROM STRING_CNT;
OCCURRENCE
1.66666667
<br>
Sidenote: Please give a try before posting..<br>
And you are posting a wrong solution after a TESTED right solution posted hours before..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Getting count of occurances of a string in a within a string

    Dear all,
    I want to find how many times the particular number 11 is present in the string ',11,12,13,14,11,16,17,11,23,11,'.
    expected answer 3.
    Please help me to write the sql statement.
    SQL> select length(regexp_replace(',11,12,13,12,11,', '[^11]')) / length('11') cnt from dual;
           CNT
           3.5
    tried the above one but no luck.
    Regards
    Rajat

    regexp_count ... But I see 4 11's .. Did I miss anything?
    SELECT REGEXP_COUNT (',11,12,13,14,11,16,17,11,23,11,', ',11,') FROM DUAL;
    Cheers,
    Manik.

  • To get the count of records and able to access the column value in a single

    Hi
    Is there any way to get the number of records in the query and access the column values
    e.g
    select count(*)
    from
    (SELECT department, COUNT(*) as "Number of employees"
    FROM employees
    WHERE salary > 25000
    GROUP BY department ) a
    This wil only get the Count, if i want to access each row from the inline view how can i do that.

    Your question is not clear.
    Are you looking for total record count as well as count by department ?
    Something like this?
    SQL>
    SQL> with temp as
      2  (
      3  select 1 dept ,10000 sal from dual union
      4  select 1 dept ,25100 sal from dual union
      5  select 1 dept ,30000 sal from dual union
      6  select 1 dept ,40000 sal from dual union
      7  select 2 dept ,10000 sal from dual union
      8  select 2 dept ,25100 sal from dual union
      9  select 2 dept ,30000 sal from dual union
    10  select 2 dept ,40000 sal from dual )
    11  select count(*) over( partition by 1 ) total_count,dept,
    12  count(*) over(partition by dept) dept_cnt  from temp
    13  where sal>25000;
    TOTAL_COUNT       DEPT   DEPT_CNT
              6          1          3
              6          1          3
              6          1          3
              6          2          3
              6          2          3
              6          2          3
    6 rows selected
    SQL>

  • Append string to each column value

    Version:11.2
    create table test1 (name1 varchar2(10));
    insert into test1 values ('JUPITER');
    insert into test1 values ('EARTH');
    insert into test1 values ('MARS');
    insert into test1 values ('VENUS');
    commit;
    SQL> select * from test1;
    NAME1
    JUPITER
    EARTH
    MARS
    VENUSFor each values of this table, I want three rows to be returned with the string
    JUPITER is a planet
    JUPITER is almost round
    JUPITER revolves around the sun
    EARTH is a planet
    EARTH is almost round
    EARTH revolves around the sun
    MARS is a planet
    MARS is almost round
    MARS revolves around the sun
    .Any idea how I could do this ?

    You'll need to cross join a set of three rows to your base table.
    There are different ways to do it, for example :
    SQL> select name1 ||
      2         case n when 1 then ' is a planet'
      3                when 2 then ' is almost round'
      4                when 3 then ' revolves around the sun'
      5         end as final_name
      6  from test1
      7       cross join (
      8         select level n
      9         from dual
    10         connect by level <= 3
    11       )
    12  order by 1
    13  ;
    FINAL_NAME
    EARTH is a planet
    EARTH is almost round
    EARTH revolves around the sun
    JUPITER is a planet
    JUPITER is almost round
    JUPITER revolves around the sun
    MARS is a planet
    MARS is almost round
    MARS revolves around the sun
    VENUS is a planet
    VENUS is almost round
    VENUS revolves around the sun
    12 rows selected
    SQL> select name1 || text as final_name
      2  from (
      3    select name1
      4         , ' is a planet' as text1
      5         , ' is almost round' as text2
      6         , ' revolves around the sun' as text3
      7    from test1
      8  )
      9  unpivot (text for text# in (text1, text2, text3))
    10  ;
    FINAL_NAME
    JUPITER is a planet
    JUPITER is almost round
    JUPITER revolves around the sun
    EARTH is a planet
    EARTH is almost round
    EARTH revolves around the sun
    MARS is a planet
    MARS is almost round
    MARS revolves around the sun
    VENUS is a planet
    VENUS is almost round
    VENUS revolves around the sun
    12 rows selected

  • Count the occurance of a character in a string

    What is the function to count the occurance of a character in a string.
    like 'test test1 test2 test3' with in this string there are 3 white spaces.
    instr will give the first one, replace will change the all... and what's for the occurance (number of white spaces, which is 3 in this case) count
    Message was edited by:
    gladnn

    SQL> var a varchar2(25)
    SQL> exec :a := 'gghhhh999jjjj'
    &nbsp
    PL/SQL procedure successfully completed.
    &nbsp
    SQL> select length(:a) - nvl(length(replace(:a,'h','')),0) from dual;
    &nbsp
    LENGTH(:A)-NVL(LENGTH(REPLACE(:A,'H','')),0)
                                               4Rgds.

  • Program to count the no. of times a character occurs in a string.

    program to count the no. of times a character occurs in a string.
    Say if u have a method :- Countclass(string s,char c) then using this u should be able to count a char ' T' in the string ="TESTING".
    So it is appering 2 times.
    How to count it.

    int countChar(String s, char c) {
       int count = 0;
       for (int i=0; i<s.length(); i++) {
          if (s.charAt(i) == c)
             count++;
       return count;
    }

  • Get-Counter : The \\ServerNameHere\\SQLSERVER:Locks(_Total)\Lock Waits/sec performance counter path is not valid.

    I have the following code:
    Import-Module "sqlps" -DisableNameChecking
    #####http://www.travisgan.com/2013/03/powershell-and-performance-monitor.html
    function ExtractPerfmonData 
        param(
            [string]$server,
            [string]$instance
        [Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet]$collections
        $monitorServer = "MonitoringServerNameHere"
        $monitorDB = "MonitoringDatabaseNameHere"
        $counters = @(
            "\$($instance):Memory Manager\Memory Grants Pending",
            "\$($instance):Memory Manager\Target Server Memory (KB)",
            "\$($instance):Memory Manager\Total Server Memory (KB)",
            "\$($instance):Buffer Manager\Buffer Cache Hit Ratio",
            "\$($instance):Buffer Manager\Checkpoint pages/sec",
            "\$($instance):Buffer Manager\Page Life Expectancy",
            "\$($instance):General Statistics\User Connections",
            "\$($instance):General Statistics\Processes Blocked",
            "\$($instance):Access Methods\Page Splits/sec",
            "\$($instance):SQL Statistics\Batch Requests/sec",
            "\$($instance):SQL Statistics\SQL Compilations/sec",
            "\$($instance):SQL Statistics\SQL Re-Compilations/sec",
            "\$($instance):Locks(_Total)\Lock Waits/sec"
        $collections = Get-Counter -ComputerName $server -Counter $counters -SampleInterval 1 -MaxSamples 1
        $sampling = $collections.CounterSamples | Select-Object -Property TimeStamp, Path, Cookedvalue
        $xmlString = $sampling | ConvertTo-Xml -As String
        $query = "dbo.usp_InsertPerfmonCounters_SQLServer '$xmlString';"
        Invoke-Sqlcmd -ServerInstance $monitorServer -Database $monitorDB -Query $query
    #####ExtractPerfmonData -server "YourRemoteServerName" -instance "MSSQL`$SQLTest"
    ExtractPerfmonData -server "ServerName1Here" -instance "SQLSERVER" 
    ExtractPerfmonData -server "ServerName2Here" -instance "SQLSERVER"
    ExtractPerfmonData -server "ServerName3Here" -instance "MSSQL`$InstanceNameHere"  
    ExtractPerfmonData -server "ServerName4Here" -instance "SQLSERVER" 
    (I have 93 instances listed; here I just gave a sample of 4.)
    For only one instance I get the following error message:
    Get-Counter : The
    \\ServerNameHere2\\SQLSERVER:Locks(_Total)\Lock Waits/sec performance counter path  is not valid.
    All of the instances should have been set up the same, so I am confused as to why this error only occurs on this one instance.  I do not know where to look.  Has anyone ever seen this type of error before?
    lcerni

    Here is the output of the first script:
    CounterSetName                                                                                                                     
    ...       (eliminating non sql server counters here)              
    SQLAgent:Alerts                                                        
    SQLAgent:Jobs                                                          
    SQLAgent:JobSteps                                                        
    SQLAgent:Statistics                                      
    SQLServer:Access Methods                                                                                          
    SQLServer:Availability Replica  SQLServer:Backup Device                                                                                                            
    SQLServer:Batch Resp Statistics                                                                                                    
    SQLServer:Broker Activation                                                                                                        
    SQLServer:Broker Statistics                                                                                                        
    SQLServer:Broker TO Statistics                                                                                                     
    SQLServer:Broker/DBM Transport                                                                                                     
    SQLServer:Buffer Manager                                                                                                           
    SQLServer:Buffer Node                                                                                                              
    SQLServer:Catalog Metadata                                                                                                         
    SQLServer:CLR                                                                                                                      
    SQLServer:Cursor Manager by Type                                                                                                   
    SQLServer:Cursor Manager Total                                                                                                     
    SQLServer:Database Mirroring                                                                                                       
    SQLServer:Database Replica                                                                                                         
    SQLServer:Databases                                                                                                                
    SQLServer:Deprecated Features                                                                                                      
    SQLServer:Exec Statistics                                                                                                          
    SQLServer:FileTable                                                                                                                
    SQLServer:General Statistics                                                                                                       
    SQLServer:Latches                                                                                                                  
    SQLServer:Locks                                                                                                                    
    SQLServer:Memory Broker Clerks                                                                                                     
    SQLServer:Memory Manager                                                                                                           
    SQLServer:Memory Node                                                                                                              
    SQLServer:Plan Cache                                                                                                               
    SQLServer:Query Execution                                                                                                          
    SQLServer:Replication Agents                                                                                                       
    SQLServer:Replication Dist.                                                                                                        
    SQLServer:Replication Logreader                                                                                                    
    SQLServer:Replication Merge                                                                                                        
    SQLServer:Replication Snapshot                                                                                                     
    SQLServer:Resource Pool Stats                                                                                                      
    SQLServer:SQL Errors                                                                                                               
    SQLServer:SQL Statistics                                                                                                           
    SQLServer:Transactions                                                                                                             
    SQLServer:User Settable                                                                                                            
    SQLServer:Wait Statistics                                                                                                          
    SQLServer:Workload Group Stats                                                                                                     
    ...       (eliminating non sql server counters here)
    lcerni

  • [Question]how to count the occurance of numbers inside the array

    im just practicing my java skill but i cant get my program work can you give me guys some idea on how to determine a number that occured more than 1 inside the array e.g i have 10 elements and inside of my offset i have
    1,2,5,4,5,6,5,8,9,5
    and what im planning to do is count the occurances of the number who occures more than 1 and for that 5 occur 3 times how my program can know that i use for loop but cant figure out how to filter the occurances of numbers inside
    my offset
    thank's

    Encephalopathic you said put - 1 instead i did - 2
    public class sample
       public static void main(String args[])
          int num[] = {2,2,2};
          int index1, count = 0, find = 0;
          for(index1 = 0; index1 < num.length - 2; index1++)
             for(int index2 = 0; index2 < num.length; index2++)
                if(num[index2]==num[index1])
                  find = num[index2];
                  count++;
             System.out.println("i found " + find + " " + count + " same number inside your offset");
    }output is:
    i found 2 3 same number inside your offset
    but another question is what if i want my program to tell the other number that occur 1 time
    like this:
    i found 1 2 same number inside your offset
    i found 2 0 same number inside your offset
    i found 1 2 same number inside your offset

  • Mapping Query : Can I get the Number Occurance of a segment

    Can I get the Number Occurance of a segment
    Source MSG
    Tree             Occurence
    **File_Message    (1..1)
    .....Name         (1..1)
    .....Sal          (1..1)
    .....**Details    (1..Unbound)   
    .........MailID   (1..1) 
    .........MobileNO (1..1)     
    Target MSG
    **CountDetails   (1..1)
    .....Count       (1..1)
    In Target MSG, I want the number of occurance of the FileDeatils-->Details 
    if source file is like follow
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:File_Message xmlns:ns0="urn:test:ns:ns">
       <Nam>John</Nam>
       <Sal>2342</Sal>
       <Details>
          <MailID>[email protected]</MailID>
          <TelNo>345345345</TelNo>
       </Details>
       <Details>
          <MailID>[email protected]</MailID>
          <TelNo>888888888</TelNo>
       </Details>
    </ns0:File_Message>
    I need to get the taget Message as follow
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:CountDetails xmlns:ns0="urn:test:ns:ns">
       <Count>2</Count>
    </ns0:CountDetails>
    in Count Tag I should get the number of occurance of Details Tag in source MSG
    Can any one help regard this
    Thanks is advance

    Hai Mohan,
       My Real Problem is
    I am Using the Scenario File--> XI --IDoc (Using BPM)
    File is having the following value
    Header Details (one Occurance)
    PO(1..Unbound)
    for Example that file having 2 PO (Purchase Order) Then I have to split that file in to two files..
    and I have to pass that two files to Post Idoc(0rders02) for create sal Order.
    That file may have more than one PO
    Please give Ur Suggest me on this
    Thanks in advance
    Dhanabal T

  • Get Count of a Delimeter

    10g, RH Linux
    I have a ^-delimited string as a col value. What's the best way to get the count of carets ( ^ ) in each string?
    Thanks,

    One way could be:
    SQL> With T as(
      2   Select 'asdkjh^^^^asdas^sdf!sdf^' c1 from dual union all
      3   Select '23~^wtr^w3413sdf!sdf^' from dual union all
      4   Select 'asdkjh^^32ert4^SGhh' from dual union all
      5   Select '^^^^^^^^^^^^^^^^^^^' from dual union all
      6   Select '121111111111123333' from dual )
      7  Select C1,
      8         length(c1) - nvl(length(replace(c1,'^',null)),0) "Caret Count" from T;
    C1                       Caret Count
    asdkjh^^^^asdas^sdf!sdf^           6
    23~^wtr^w3413sdf!sdf^              3
    asdkjh^^32ert4^SGhh                3
    ^^^^^^^^^^^^^^^^^^^               19
    121111111111123333                 0
    SQL>

  • Getting multiple counters with get-counter ?

    Just trying to get a handful of counters for sql server monitoring.  but is there any way i can export-counters all  into 1  .blg file or am i not getting this ?  do they have to be in the same set i guess is the question.
    Counters like :
    Get-Counter "\\$computer\processor(_total)\% processor time"
    Physical Disk: Average Disk/sec Reads
    Physical Disk: Average Disk/sec Write
    SQL Server: Memory Manager >> Free List Stalls/sec
          SQL Server: Memory Manager >> Memory Grants Pending
    thanks,
    Chris

    Mike, once again, thanks.
    I guess i need to find out how to read the cmdlet powershell syntax.  from the documentation that you've sent, and which i've read before, i can't find where you can comma separate counters.  clearly, i need to decipher the syntax which is not
    too clear.
    That is why it is important to take a course or read a book or use the training materials on this site. The raining answers these obvious questions. It is like buying a new car - first you read the owners manual.
    In the first couple of lessons the syntax of the CmdLets are explained.
    You can also use help to discover how they work.
    The CmdLets shows you how to call a CmdLet with an array of strings.  A comma separated list of any kind is an array.
    (1,2,3,43,5).GetType()
    ¯\_(ツ)_/¯

  • Ordering of objects by more than one field and get counts

    i have an object visit (personid, city, street, place, date)
    A person could have visited a same place in the same strret in the same city several times on different dates.
    I have a visits 'Set' for a person and I have to get a count of visits he has done to a place..
    its basically select count(visits) group by city, street , place.
    I know to use interface comparator for a single field.. how to compare multiple fields and get counts??
    if you know abt where i can find information please let me know.
    Thanks.

    For multiple fields, your comparator compares the most significant field first. If they're unequal, it returns +/- accordingly. If they're equal, then it moves on to the next field. And so on, until, finally, if all the relevant fields are equal, then the objects are equal.
    Just like what you do when comparing, say, last names. If the first letters are unequal, you're done, else move onto the next letter, and so on..
    For the count, you wouldn't use a comparator, as that's for sorting. Exactly how you do it depends on the details of what you're storing and how, which you haven't provided.

  • Trying to convert a word file to pdf and keep getting "An error occured while signing in"?

    Trying to convert a word file to pdf and keep getting "An error occured while signing in"?

    Or contact Adobe Customer Service via http://helpx.adobe.com/contact.html?product=export-pdf

  • Why do I get "Error 1 occured at Config Data Registry.vi(get data) invalid object 0" while starting my application?

    Why do I get "Error 1 occured at Config Data Registry.vi(get data) invalid object 0" when starting my application created in LabVIEW 7.1?  I am starting the application in a PXI rack running Windows XP.  I have an executable written in LabVIEW 7.0 that runs without this error.  After clicking the Continue button in the error, the application seems to continue happily.
    Is there something I need to include when I make the executable?
    I would like to understand and eliminate this start up error.
    Thanks in advance.
    BobNorth

    Hi Bob,
    I looked through the program and I figured out where the error is coming from, and potentially what is causing it. In a lot of the cases of the program you are searching a 1-D array for the name of the case, and if you don't find it then it skips the function and gives "Error 1 occurred at Config Data Registry.vi(CASENAME) invalid object 0". I attached a screenshot that shows what I mean. The Search 1-D Array.vi is returning a -1 which means it didn't find the case. The reason I believe this is happening is because the shift register for that array is not initialized. While the other cases "reset" and "register" interact with the array shift registers and most likely create the array you need, if the program defaults to the "get data" case then it will try to run that before registering and won't have an array to search. This would also explain why it only has this problem at first and seems to run just fine after that. To fix this you should either make an initial array and wire it into the shift register or make the "reset" case the default as opposed to the "get data" case.
    Regards,
    Peter W.
    Attachments:
    Config Data Registry.png ‏55 KB

  • Move to new computer, get "An error occurred while reading files or writing files to disc. The disc

    I tried to move my PE6 install and catalog to a new computer.  It was on a Dell Windows XP machine, and I moved it to a Toshiba Windows 7 (64 bit) machine.  I have always kept my photo files on an external hard drive.  My photo library is 50GB, 10,000 files.  Here is what I did.
    Copied the original PE6 install file to the Toshiba.  Installed but didn’t activate it.
    Copied the entire My Catalog folder to the proper Windows 7 location.
    Plugged the external drive into the Toshiba.  Made sure the same drive letter as before (E).
    Fired up PE6 on Toshiba.  Looked good in Organizer.  Everything seemed to be there, but I didn't try to make changes at that point.
    Deactivated PE6 on the Dell.  Activated on the Toshiba.
    Then I realized that it is not right.  I can edit Keywords and Rating stars on the pics, but not dates, captions or notes.  I get “An error occurred while reading files or writing files to disc. The disc may be full or there may be problems with the source media.”
    Only a fraction of the external drive is in use.
    I can access the files on the external drive with another app (Windows Photo Viewer).
    I tried Reconnect All Missing Files.  Somewhat ambiguously, it says “There are no files to reconnect.”
    In the properties in the Organizer for each picture are the proper file names and paths.  Folder view works fine in Organizer.
    I can put new files in the same external drive directories, import them into PE6, then edit them normally.
    What is the easiest way to get Organizer properly connected to my files?  I suppose I could reimport all the pics on the new machine, but I assume I'd lose some of my metadata.  So that is out of the question.
    Thanks,
    Bill

    Are you sure that file paths are correct? I say this because under XP they would have originally pointed to Documents & Settings/My Pictures whereas on W7 it will be User/Pictures, albeit you are using an external hd.
    Take a look at this knowledge base note on the correct procedure for back-up and restore.
    I think writing metadata to files for such a large catalog will be a thankless task.
    http://helpx.adobe.com/photoshop-elements/kb/backup-restore-move-catalog-photoshop.html

Maybe you are looking for

  • When  i try to access my email on my ipad using safari i cant get thru

    i have an ipad 2. when i go to a home page using safari, i can not click a link and go to the next page it only partial loads

  • Diablo III Trophy List!

     Welcome to the Diablo III Trophy List! Diablo III is an epic fantasy RPG! So theres knights and wizards, potions and hoarding treasure, all in third-person with quite a bit of co-oping. The trophy list is full-up with mission and story based trophie

  • Some DSC developing relating questions

    Hi, I am new with DSC and have some questions relating to building the custom periodic I/O DSC server: 1. After building the custom VI and implementing it as an I/O DSC server, I found there are some mistakes inside the custom VI. I would like to mod

  • Time Related Dimension(table) in communication data model

    Hi, The most common and important thing for a communication data model to me is time metrics. Things like mean up time, or mean down time are common KPIs we are tracking. To make this model efficient, we need to create a time dimension can precisely

  • How many TVs on one box?

    Even though this is one of the FAQs on the main site, the jump tag does not go to the answer. I have 3 boxes and 3 TVs, but want to add two more TVs. What is the best solution? Can I exchange one of the boxes for a Home Media box and have 3 boxes con