How to get a distinct count of multiple columns

I've done this before and I'll be darned why I can't recall this.
Table with 3 columns with the primary key defined in column a.
Row a b c
num.
1 020 how abc
2 030 why def
3 010 not ghi
4 040 how abc
5 050 yes def
6 060 why def
So what I want is a count of the unique values for columns b and c as if b and c were actually one field.
So the result of the query would be:
Count = 4 unique rows.
Hopefully I'm making some sort of sense. It's a bit much to ask about the number of occurrences of each duplicate value, I'm sure just getting count of the unique rows of the non-indexed rows will be sufficient. Since the query is meant to be universal for multiple columns of numeric and alphanumeric data and can be expanded for multiple columns, I am simply trying to get a basic skeleton that works for an "on the fly" analysis.

Thanks to all of you. I had the idea and just couldn't nail it down. You did it.
All of you understood what I poorly communicated. My apologies for the lack of prep with a table, I was running patches on the system and couldn't dare interrupt it on my laptop and starting Oracle 11 while Micro$lop was patching all sorts of evil code. This is something I'm setting up on my own time so it's a work I'm going to try to be proud of. So there will be plenty of instrumentation and debugging code for timing.
I'd thought of concatenating columns and was worried it wouldn't backport to older Oracle versions (work goes back to 8.1.7) with nulls and other goofy things like long raw fields or lob/clobs plus the other DBs that are at various sites. What I'm trying to do is improve on a crappy data analysis tool SAP provides to use with reporting unique columns. (Basis people could recognize this as DB05). I tried dragging out the SQL that their ABAP/4 language generates from an SQL trace but it was unusable and often dies on internal storage which on most sites is about 4GB per process. Needless to say, the program is wasteful and I'm trying to keep the work on the DB where it belongs and discourage cowboys from doing this in the DB on the fly and at the same time make it simpler for junior members to use while having a semblance of an audit trail.
What I'm trying to do is work out a tool that checks all the crappy secondary indexes that were created by folks who seem to think in ways that are from an alien species not yet speculated about even with the strongest psychedelics. One of them actually decreases performance by a minimum factor of 5. It's not much when it's 5 seconds but when the response time averages about 3 hours beforehand, you can imagine what it was like afterward. In this particular case, the "logic" was that the index needed to be defined by the order of the fields of the select clause. Some myths never die. So it's not easy to work out which ones haven't been used in a long time, so it's down to finding which of the custom ones are actually bad in terms of selectivity. Some of these may have made a little bit of sense when the system was started up, now that some of these have millions of rows instead of a few thousand, thaw tend to expose the flaws in design.
I'm also trying to make this work on multiple DBs such as DB2, MaxDB and (sob) SQL Squealer. The idea is to write this in ABAP code as a utility without the overhead of internal tables in ABAP as some of these tables are many millions of rows and I have to account for the size in memory. (ABAP field sizes in internal memory are generally much larger than the actual DB lengths. so every bit helps!) So I'm trying to create actual SQL on the fly and use it internally without going through the SAP DB interface which limits the type of SQL functions used and all the overhead. It's intended to grab a secondary index and if there are more than 2 fields defined, work it backwards to show unique values for all columns, all columns - 1, all columns - 2 and so on back to the initial column in the index.
Why does this seem important? On Oracle I can generate histograms but those can often screw up SAP. On other DBs, the indexing cardinality is much more important, particularly with DB optimizers that make some odd decisions. So I need evidence I can push to folks who will only understand if there's a plain and simple analysis that explains it (almost) in crayon.
I'm testing null values next (which worked!) but these suggestions all seem to follow the same idea which won't work in ABAP without some serious memory issues. So I'm down to this type of coding:
exec sql.
<dynamically generated true SQL>
end-exec.
rather than using ABAP with their concept of "open SQL" and the DB interface with all the overhead.
RB's suggestion of the UNION ALL wasn't quite what I was looking for BUT it made me think that this would be a nice enhancement for evaluations!
So the candidates that seem to work for what I wanted are as follows:
SQL> SELECT COUNT (MIN (0)) AS distinct_col3_col4_cnt
2 from rb group by b, c;
DISTINCT_COL3_COL4_CNT
7
select count(distinct(b || c)) num_rows from rb;
So thanks also to Frank, APNL and Nimesh for their examples. Now the fun starts as I spec out the processing.

Similar Messages

  • How to get Select All or select Multiple columns  in OOALV

    HI Experts
    i'm assignig internal table to dynamic internal table(FS_IST_TABLE) for to display the output.
    but i'm not geting the Select ALL Option. and i can't select multiple columns at a time.
    where i can select only one column.
    how can i select multiple columns.
    please any one help me.
    regrads,
    rathan.

    Hi,
      If we want to select the multiple columns in the alv by using ooabap
    so in the class CL_GUI_ALV_GRID  it is having one method SET_TABLE_FOR_FIRST_DISPLAY
    it is having one importing parameter IS_LAYOUT of type lvc_s_layo type
    and this structure contains one field SEL_MODE and set that field value as 'A'.
    then we can select the multiple rows in alv grid

  • Distinct count on multiple columns

    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    select  distinct USERID,REG_DATE,COUNT(*) CNT from REGISTRATION where TRUNC(REG_DATE)>TO_DATE('01-NOVEMBER-2012','DD-MONTH-YYYY')
    and REG_ID not in (select REG_ID from REG_SEG_CAT) group by USERID,REG_DATE  
    41     27-NOV-12     1
    43     27-NOV-12     1
    43     27-NOV-12     1any idea how to show count=2 for userid 43
    Edited by: 946207 on Dec 4, 2012 2:11 PM

    Hi,
    How could we know if you don't show us your input data?
    Please read SQL and PL/SQL FAQ
    Additionally when you put some code please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How do you count the multiple columns of a field in a table

    How do you count the multiple columns of a field in a table

    Hi,
    4396bf34-e890-4202-a6b0-4e08c9ff0e89 wrote:
    How do you count the multiple columns of a field in a table
    Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002
    "Field" isn't a standard database term.  Some people say "field" when they mean "column", but I don't think that's what you mean ("How do you count the multiple columns of a column ..").  Do you want to know how many times a column is used (as opposed to NULL), or the number of different values in a column?  You really need to show what you want.

  • How to get file line count.

    Hey guys,
    How to get file line count very fast? I am using BufferedReader to readLine() and count. But when dealing with big file, say several GB size, this process will be very time consuming.
    Is there any other methods?
    Thanks in advace!

    What I'd do is you create an infofetcher, register a listener, implement gotMore() and have that scan for '\n'
    Some might suggest getting rid of the listener/sender pattern or use multiple threads to make ii faster. This might help a little, but only if your I/O is super-duper speedy.
    you are welcome to use and modify this code, but please don't change the package or take credit for it as your own work.
    InfoFetcher.java
    ============
    package tjacobs.io;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    * InfoFetcher is a generic way to read data from an input stream (file, socket, etc)
    * InfoFetcher can be set up with a thread so that it reads from an input stream
    * and report to registered listeners as it gets
    * more information. This vastly simplifies the process of always re-writing
    * the same code for reading from an input stream.
    * <p>
    * I use this all over
         public class InfoFetcher implements Runnable {
              public byte[] buf;
              public InputStream in;
              public int waitTime;
              private ArrayList mListeners;
              public int got = 0;
              protected boolean mClearBufferFlag = false;
              public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
                   this.buf = buf;
                   this.in = in;
                   this.waitTime = waitTime;
              public void addInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        mListeners = new ArrayList(2);
                   if (!mListeners.contains(fll)) {
                        mListeners.add(fll);
              public void removeInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        return;
                   mListeners.remove(fll);
              public byte[] readCompletely() {
                   run();
                   return buf;
              public int got() {
                   return got;
              public void run() {
                   if (waitTime > 0) {
                        TimeOut to = new TimeOut(waitTime);
                        Thread t = new Thread(to);
                        t.start();
                   int b;
                   try {
                        while ((b = in.read()) != -1) {
                             if (got + 1 > buf.length) {
                                  buf = IOUtils.expandBuf(buf);
                             int start = got;
                             buf[got++] = (byte) b;
                             int available = in.available();
                             //System.out.println("got = " + got + " available = " + available + " buf.length = " + buf.length);
                             if (got + available > buf.length) {
                                  buf = IOUtils.expandBuf(buf, Math.max(got + available, buf.length * 2));
                             got += in.read(buf, got, available);
                             signalListeners(false, start);
                             if (mClearBufferFlag) {
                                  mClearBufferFlag = false;
                                  got = 0;
                   } catch (IOException iox) {
                        throw new PartialReadException(got, buf.length);
                   } finally {
                        buf = IOUtils.trimBuf(buf, got);
                        signalListeners(true);
              private void setClearBufferFlag(boolean status) {
                   mClearBufferFlag = status;
              public void clearBuffer() {
                   setClearBufferFlag(true);
              private void signalListeners(boolean over) {
                   signalListeners (over, 0);
              private void signalListeners(boolean over, int start) {
                   if (mListeners != null) {
                        Iterator i = mListeners.iterator();
                        InputStreamEvent ev = new InputStreamEvent(got, buf, start);
                        //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                        while (i.hasNext()) {
                             InputStreamListener fll = (InputStreamListener) i.next();
                             if (over) {
                                  fll.gotAll(ev);
                             } else {
                                  fll.gotMore(ev);
    InputStreamListener.java
    ====================
    package tjacobs.io;
         public interface InputStreamListener {
               * the new data retrieved is in the byte array from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
              public void gotMore(InputStreamEvent ev);
               * reading has finished. The entire contents read from the stream in
               * in the buffer
              public void gotAll(InputStreamEvent ev);
    InputStreamEvent
    ===============
    package tjacobs.io;
    * The InputStreamEvent fired from the InfoFetcher
    * the new data retrieved is from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
    public class InputStreamEvent {
         public int totalBytesRetrieved;
         public int start;
         public byte buffer[];
         public InputStreamEvent (int bytes, byte buf[]) {
              this(bytes, buf, 0);
         public InputStreamEvent (int bytes, byte buf[], int start) {
              totalBytesRetrieved = bytes;
              buffer = buf;
              this.start = start;
         public int getBytesRetrieved() {
              return totalBytesRetrieved;
         public int getStart() {
              return start;
         public byte[] getBytes() {
              return buffer;
    ParialReadException
    =================
    package tjacobs.io;
    public class PartialReadException extends RuntimeException {
         public PartialReadException(int got, int total) {
              super("Got " + got + " of " + total + " bytes");
    }

  • How to get the row Count of a ResultSet

    How to get the row Count of a ResultSet

    Hi
    I'v tried rennie1's way ,but I only get zero,my code is:
    rs.executeQuery("select count(*) from t_test");
    if (rs.next()) int rowCount=rs.getInt(1);
    I also tried barni's way ,but the method rs.last() and rs.beforeFirst() throw a same Exception
    I tried another way,the code is:
    while rs.next(){
    // Do nothing ,just move the cursour to the last row
    int rowCount=rs.getRow()
    However,the rowCount still equal zero
    Any help would be greatly apprecite!
    note:
    I get connection by DataSource's JNDI name from client, the Server is Weblogic Server 6, the DBMS is Oracle.

  • How to get  visible row  count  in JTable ?

    I have one table which is added to one scroll pane. For example my table have total 1000 rows, but at a time only 20 rows should be visible to the scroll pane. And I want to scroll the rows and show only 20 at a time.When user scrolls JTable then next time he can view only 1 to 21, then 2 to 22, and so on. I want to know how to get that number which represents the visible row( in this case it is 20).So kindly help me how to get visible row count. Any help regarding this will be appriciated.
    Thanks and Regards,
    Sheetal

    how to get visible row count.First you need to get the viewport used by the scrollpane. Then you can use methods like getViewPosition() and getViewSize() to get information about the current postition of and size of the viewport.
    Then you can use the table method getRowAtPoint(). to determine the first and last visible row which can then be used to calculate the visible row count.
    When user scrolls JTable then next time he can view only 1 to 21, then 2 to 22, and so onThis is the default behaviour when a "block" scroll is done.
    However when you click on the arrow button on the scrollbar it will only scroll a single row. You could override the getScrollableUnitIncrement() method to return the value from the getScrollableBlockIncrement() method.
    However the user can still drag the scrollbar manually which would cause a problem. So you would also need to remove the MouseMotionListeners from the scrollbar to prevent this.

  • How to get succesfullt loaded count in forall

    hi,
    plz tell me how to get succefuly loaded count into a table if i m using bulk collect & forall .

    Check out the documentation:
    Counting Rows Affected by FORALL with the %BULK_ROWCOUNT Attribute
    The cursor attributes SQL%FOUND, SQL%ISOPEN, SQL%NOTFOUND, and SQL%ROWCOUNT, return useful information about the most recently executed DML statement. For additional description of cursor attributes, see "Implicit Cursors".The SQL cursor has one composite attribute, %BULK_ROWCOUNT, for use with the FORALL statement. This attribute works like an associative array: SQL%BULK_ROWCOUNT(i) stores the number of rows processed by the ith execution of an INSERT, UPDATE or DELETE statement.

  • How to get all the values in one column of a JTable

    How to get all the values in one column of a JTable as a Collection of String.
    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column.

    I don;t want to write a for loop to say getValueAt(row, 1) eg for 2nd column. You could always write a custom TableModel that stores the data in the format you want it. It would probably be about 50 lines of code. Or you could write a loop in 3 lines of code. I'll let you decide which approach you want to take.

  • How to calculate the individual sums of multiple columns in a single query

    Hello,
    Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
    Will appreciate any help or suggestion.
    Thanks

    user13667036 wrote:
    Hello,
    Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
    Will appreciate any help or suggestion.
    ThanksLooks like you want a simple group by.
    select
              yr
         ,      mnth
         ,      region
         ,     sum(handled_package)
         ,     sum(expected_missing_package)
         ,     sum(actual_missing_package)
    from test
    group by
         yr, mnth, region
    order by      
         yr, mnth, region;I wouldn't recommend storing your data for year / month in 2 columns like that unless you have a really good reason. I would store it as a date column and add a check constraint to ensure that the date is always the first of the month, then format it out as you wish to the client.
    CREATE TABLE test
         year_month                              date,
        Region                     VARCHAR2(50),
        CITY                       VARCHAR2(50),             
        Handled_Package            NUMBER,       
        Expected_Missing_Package   NUMBER,   
        Actual_Missing_Package     NUMBER
    alter table test add constraint firs_of_month check (year_month = trunc(year_month, 'mm'));
    ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
      2  Values (to_date('2012-nov-12', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
    Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
    ERROR at line 1:
    ORA-02290: check constraint (TUBBY.FIRS_OF_MONTH) violated
    Elapsed: 00:00:00.03
    ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
      2  Values (to_date('2012-nov-01', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
    1 row created.
    Elapsed: 00:00:00.01
    ME_XE?select
      2        to_char(year_month, 'fmYYYY')    as year
      3     ,  to_char(year_month, 'fmMonth')   as month
      4     ,  Region
      5     ,  CITY
      6     ,  Handled_Package
      7     ,  Expected_Missing_Package
      8     ,  Actual_Missing_Package
      9  from test;
    YEAR         MONTH                REGION                         CITY                    HANDLED_PACKAGE EXPECTED_MISSING_PACKAGE ACTUAL_MISSING_PACKAGE
    2012         November             Western                        San Fransisco                       200                       10                      5
    1 row selected.
    Elapsed: 00:00:00.01
    ME_XE?Then you have nice a nice and easy validation that ensures you data integrity.
    Cheers,

  • How to get payment document number from paid column in monthly invoice

    Dear experts
    I use SBO japan version and i need to know how to get payment document number from paid column in monthly invoice ?
    in table MIN1, only contain invoice and credit note document number, there is no payment document number
    thank you for your help
    Best Regards
    JeiMing

    Dear Gordon
    Yeah, you are right, i can use field MIentry in RCT2
    thank you
    Best regards
    jeiming

  • How to get the index of a h:column element?

    Hi!
    I'd like to know how to get the index of a <h:column> element.
    Here is the code of what I'm trying to do:
    <h:column>
         <a:commandLink
              value="#{familyAction.familyDocsByPrj}"
              action="#{homeAction.search(ROW_INDEX)}"
              reRender="rightAppPanel" />
    </h:column>When clicking a row, I'd like to make a "search" depending on the selected row.
    Does anybode know how to do that?
    Thanks a lot :)

    Thanks a lot for all your answers! :)
    I finally got to do something with my little knowledge =P
    I created a new class containing all the data needed for the dataTable (including a "String id").
    And that's what I get:
    <h:column>
         <a:commandLink
              value="#{familyAction.familyDocsByPrj.name}"
              action="#{homeAction.search(familyAction.familydocsByPrj.id)}"
              reRender="rightAppPanel" />
    </h:column>

  • How to get the input value as a columns headings of the kye figer

    Dear all,
    the senario is i have keyfiger heading like DESPATCHES MADE ON (0CALDAY) and CUMMULATIVE DESPATCHES FOR (0CALMONTH), the 0CALDAY is the input value of the report. so how to get the value of the 0CALDAY and 0CALMONTH in the heading name of the key figer.
    I really appreciate for any help on this.
    wil assign pts for sure...
    thanks
    regards
    Mohan

    Dear  Venkat Ambati,Sumit Singn,Masi dandavate,
    thanks for reply.....
    ya got u r value able inputs but i don't no how to get the variable value to the column heading, if u guy's having any doc's means plz send me the same, my mail id is <u><i>[email protected]</i></u> or <i><u>[email protected]</u></i>
    thanks n regards
    Mohan

  • How to get string (specified by line and column) from txt file with labview

    Hi everyone
    How to get string (specified by line and column) from txt file with labview
    thx 
    Solved!
    Go to Solution.

    As far as I know, a text file has no columns.  Please be more specific.  Do you mean something like the 5th word on line 4, where words are separated by a space, and lines are separated by a newline character?  You could the Read from Spreadsheet String function and set the delimiter to a space.  This will produce a 2D array of strings.  Then use index array and give the line number and column number.
    - tbob
    Inventor of the WORM Global

  • File Adapter - how to get the file count from a folder

    Hi All,
    I have a requirement that have to poll a directory when the file count is reached to number N (ex:number of files avilable in folder is 5) otherwise it should wait and not pick any of the files. Is it possible to get the file count from a folder using file adapter ?? otherwise please suggest me an approach to achieve this requirement.
    Thanks,
    JJ

    Hi Sarath,
    Thank you for your reply.
    Go with the list files operation of file adapter it will gives you the number of files in the specified folder as you given. . - this step is already done.
    When the number of files reaches your count startup your webservice that which can polls the files. . . - how can i acheive this?? Have to poll the directory and process the number files - please let me know, what could be added to the webservice which is being invoked after cheking file count from parent process.
    The reason for the above question is - we cannot use ReadFile operation in second webservice because it will be automatically triggered when the file is avilable. Also SyncRead operation supports reading one file in b/w bpel process. Kindly explain me the implementation steps.
    Thanks,
    JJ

Maybe you are looking for

  • Looking for desktop calendar & contacts (not Outlook, Yahoo etc)

    I just bought my first ipod Touch. I'm looking for a stand alone calendar and address book that will sync with my Touch. I don't want to use Outlook, Gmail, Yahoo or anything like that. I use PC's with Windows XP.

  • Can't back up my new iphone 4S on computer?

    hi, I just bought my new iphone 4s,and i can't back up my iphone on itunes??i'm new to this technology.anyone help? thx.:)

  • Printing in Classic with a specific OS X printer

    Is there a way to make a Classic program print on OX equipment? Use Calendar Creator in Classic to do an extensive family & friend birthday/anniversary calendar. Have used an Epson C82 printer that recently died and replaced with a C88. Problem is th

  • Purchasing from itunes in another country

    Less a question and more a point. It is transparently ridiculous that inter-country purchases cannot be made both in terms of a service to customers to exercise choice and the 'bad taste' that these restrictive practices leave in the mouth of consume

  • User exit for order attachment

    Hi ABAPers, I receive requirement to auto populate Order status ATTC if there is there is attachment in work order, IW31/32. I looking for the best user exit that can be used for this modification. I am looking for SAP enhancement in SMOD for IW* but