PL/SQL: Count how often a value appears and subtotal it

I'm not the best at PL/SQL, but I'm trying and willing to learn.
I have some SQL that looks thru over 1 million rows in a DB and pulls back data and does decodes to make the data meaningful. My output looks like this right now
Row1 - Row2 - Row3 - Row4 - Row5
x a c d c
a c d b x
x c d b b
x x x a a
x a b b a
x = no answer
a = alpha
b = beta
c = charle
d = delta
My end goal is to try to do this: Is to try to figure out how many times x appears in a rows above, decode it from 'x' to 'no answer' and then spit out a subtotal. The same applies for A thru D as well.
Can anyone point out some PL/SQL examples that could help me out?
thanks

Two solutions
create table msw_emp
(id     varchar2(5),
row1     varchar2(1),
row2     varchar2(1),
row3     varchar2(1),
row4     varchar2(1),
row5     varchar2(1))
insert into msw_emp values('11111', 'x', 'a', 'c', 'd', 'a');
insert into msw_emp values('22222', 'x', 'a', 'a', 'd', 'd');
insert into msw_emp values('33333', 'x', 'x', 'x', 'a', 'x');
insert into msw_emp values('44444', 'a', 'a', 'a', 'a', 'b');
insert into msw_emp values('55555', 'x', 'x', 'x', 'x', 'x');
commit;
Answer Count
alpha - 9
beta - 1
charlie - 1
delta - 3
no answer - 11
#SOLUTION 1
select 'alhpa' "Answer Count",
sum(decode(row1, 'a', 1, 0)+
decode(row2, 'a', 1, 0)+
decode(row3, 'a', 1, 0)+
decode(row4, 'a', 1, 0)+
decode(row5, 'a', 1, 0)) a_count
from msw_emp
union all
select 'beta',
sum(decode(row1, 'b', 1, 0)+
decode(row2, 'b', 1, 0)+
decode(row3, 'b', 1, 0)+
decode(row4, 'b', 1, 0)+
decode(row5, 'b', 1, 0)) b_count
from msw_emp
union all
select 'charlie',
sum(decode(row1, 'c', 1, 0)+
decode(row2, 'c', 1, 0)+
decode(row3, 'c', 1, 0)+
decode(row4, 'c', 1, 0)+
decode(row5, 'c', 1, 0)) c_count
from msw_emp
union all
select 'delta',
sum(decode(row1, 'd', 1, 0)+
decode(row2, 'd', 1, 0)+
decode(row3, 'd', 1, 0)+
decode(row4, 'd', 1, 0)+
decode(row5, 'd', 1, 0)) d_count
from msw_emp
union all
select 'no answer',
sum(decode(row1, 'x', 1, 0)+
decode(row2, 'x', 1, 0)+
decode(row3, 'x', 1, 0)+
decode(row4, 'x', 1, 0)+
decode(row5, 'x', 1, 0)) x_count
from msw_emp
#SOLUTION 2
select decode(val,
'a', 'alpha',
'b', 'beta',
'c', 'charlie',
'd', 'delta',
'x', 'no answer')||' - '||count(*) "Answer Count"
from (select row1 val
from msw_emp
union all
select row2
from msw_emp
union all
select row3
from msw_emp
union all
select row4
from msw_emp
union all
select row5
from msw_emp)
group by val
Answer Count
alpha - 9
beta - 1
charlie - 1
delta - 3
no answer - 11

Similar Messages

  • How to compare value before and after

    hi,
    one of the queried Values ​​is the number of defective frames.Here, this value is compared with a previously sampled value
    If now (after 10 s) this value is bigger than previous one ,then It saves new value otherwise loop will be continue.If again after (10s) the new value is bigger than  previous  new value then again saves this new point.how can i comapre value before and after?thanks.
    Tadhika

    Do you know what a shift register is? It preserves a value from one loop iteration to the next. Please read the LabVIEW Help on shift registers. There's is also a simple example that ships with LabVIEW that will give you the basic idea (Help -> Find Examples).
    You can also use a Feedback Node in lieu of a shift register. Same concept, different implementation.

  • SubVersion in SQL Developer - how to link to packages and procedures

    My question is this - I am starting out using SubVersion in Oracle and it seems pretty straightforward to use as a source control for files that are stored in a Windows directory, that is the only way I have used it so far.
    Am I able to use it to control packages and procedures that I have saved as part of my database, ie the procedures are part of a package and the package appears within the Packages section of the appropriate connection in SQL Developer.
    I hope this makes sense.
    Cheers,
    JabJam

    Hi JabJam,
    So far, everyone is correct. SQL Developer just uses a file-based source control system (e.g., SVN), which means updating database object definitions via scripts under version control, or somehow exporting the new definition to a script so it can be version controlled after the fact. And wouldn't it be nice if the database objects could be version controlled directly. With the database developer having control over when any changes are committed for shared use in the database. Similar to using the SVN plug-in for an IDE like Eclipse for a given programming language in a shared development environment.
    But what would your DBA have to say about that? Don't most DBAs require scripts for deploying code or structural changes?
    In Oracle, definitions (DDL) are committed automatically. Anyone granted access sees them. Since you probably don't do development directly against a production database, eventually scripts (either manual or generated) will be needed for deployment to QA or production. Few mechanisms currently exist to work against an active database without other authorized users also seeing these changes.
    For DDL, the closest thing would be the fairly recent edition-based redefinition feature in 11g (R2, I think). For DML, the OWM (Oracle Workspace Management) feature would be loosely analogous.
    This is not a simple issue. Version control via an extension for Subversion provides essential basic support. Going beyond that might mean watching the evolution of edition-based redefinition, but DBAs would probably require scripts for that too.
    Regards,
    Gary
    SQL Developer Team

  • SQL LOGIC - How to accept USER input and use that data in SQL Logic?

    Hello Experts
    Can anyone of you please explain in detail how to acheive the above task am a begginner, it would be great help for me.
    Thanks in Advance.

    Hi,
    You mean to say, you need to use inputs from Data manager Prompts in your Script Logic.
    From Help File
    You can use the EvDTSModifyPkg task to dynamically pass a text string to logic in Data Manager.  For example, a user who wishes to dynamically pass a text string representing a year (which is a portion of the *XDIM_MEMBERSET instruction) could use the following steps:
    Using the EvDTSModifyPkg task, prompt for the year, i.e., PROMPT(TEXT,%TEXT%,"select a year")
    Pass the returned %TEXT% to the FormulaScript of the RunLogic task as follows: TASK(RUNLOGIC,FORMULASCRIPT,"*FUNCTION MYYEAR=%TEXT%u201D)
    In the Data Manager logic, use the dynamically created function as follows: *XDIM_MEMBERSET TIME=MYYEAR.INPUT.
    The logic name in the RunLogic task must be specified with the .LGF extension to enforce its validation at run time.
    BPC NW 2.0 Version Works differently.
    Hope this Helps,
    Kranthi

  • How to make components appear and disappear dynamically.

    So I admit I am from the HTML world and have been able to
    dynamically control divs to make them visible and invisible, as
    needed. How do you do that in Flex/Flash?
    I have tried the "visible" attribute, but the component takes
    up the same space when invisible leaving a big hole in the page --
    very surprising. I have changed the height and width to zero (which
    works) but have not been able to restore the size (since I want it
    to be width=100% and it is expecting a number, not percentage.
    So how do you implement hidden divs in Flex.
    Thanks.
    Mike

    In Flex, there is a separation between "is this component
    visible" vs. "does this component take screen space." Similar to
    the difference in CSS between "mydiv.style.visibility = 'hidden'"
    and "mydiv.style.display = 'none'".
    In Flex:
    // make it invisible
    mything.visible = false;
    // make it not take up space onscreen
    mything.includeInLayout = false;

  • How often is garbage collected and can I control it.

    The code I write tends to have a lots of graphics, video, audio all that stuff that uses lots of memory so I need to tidy up after myself. Are there any commands that force immediate collection? Any recommendations appriciated.

    So I would need CS4 to explicitly control?  I found a interesting link about garbage http://gskinner.com/talks/resource-management/    I also read that gc happens very differently in IE than FF which seems odd as they both use the same vm.

  • How to display both total and subtotal with condition on

    Hi Experts,
    We had a special requirements from our "Powerful" user for a top sales ranking report:
    say user runs for top 10 customers, query/view (It has to be built as query/views because they are going be exported to Portal) need to show
    1. sub total 10 customers
    2. total for all customers
    3. for each customer to show their sales percentage out of the overall total sales
    any recommendation welcomes
    Regards,
    Feng

    Create a condition on the Sales Key Figure as Top N and value as 10.
    So when you run the report for the Customer in Rows and Sales Key Figure in Coulmns you will get the report output for 10 customers and their respective Sales Figure. But if you see the overall result, it will be for all customers and not for only 10 customers. To get the total of only 10 customers, right click on Sales Key Figure and select Calculate result as Summation.
    Now below Sales Key Figure, create a Formula Key Figure (FKF) that will give the Total Sales for All customers. Use the formula as below
    FKF = SUMGT (SALES)
    Now create another Formula Key Figure (FKF1) that will give the % Sales with respect to total Sales. use teh Formula as below
    FKF1 = Sales %A FKF

  • How to create value table

    hi to all,
            how to create value table and provide clear document
    Thanks&Regards
    M.Suresh
    Moderator message: please search for available information/documentation.
    Edited by: Thomas Zloch on Jun 14, 2011 1:19 PM

    please search SDN before posting questions.

  • How do you and how often do you do maintanace?

    I'm poor at doing maintenance. I'd like to get into a maintenance routine and I'm looking to hear what you all do to maintain your iMac, how often you do it and any software you use to help you.
    Cheers,
    sws

    I run +Repair Disk Permissions+ on the Disk Utility +First Aid+ tab immediately before running Software Update to install any software update.
    Additionally, if the update is a system update (such as for 10.5.7), I restart from another startup disk, such as an external drive or the Mac OS X installation disc, run Disk Utility, and this time use +Repair Disk+. I have a small external drive with a minimal Leopard installation (along with TechTool Pro and some other utilities) that I use for this purpose. Then I restart normally and let Software Update install the system update.
    That is basically all the maintenance I do as a routine. I let Mac OS X take care of other "maintenance" and don't worry about it.

  • How to force simple tags and null attributes to appear when using SQL/XML?

    Hello everybody:
    I'm developing a non-schema based XMLType view.
    When the XML document is generated, i noticed two things I need to manage in order to achieve the desired result:
    1. Oracle generates a <tag></tag> pair for each XMLELEMENT defined; in my case, some tags need to appear as <tag/>... how do I do? Is it possible when using schema based XMLType views? Is it possible while using a non-schema approach?
    2. When using XMLATTRIBUTE('' AS "attribute") or XMLATTRIBUTE(NULL AS "attribute"), no one attribute with label "attribute" and null value appears at the output; how do I force to Oracle DB to render those attributes which are with no values (needed to render those attributes as another parsing code will await for all the items)?
    3. Some tip about how to route the output to an XML text disk file will be appreciated.
    Thanks in advance.
    Edited by: Enyix on 26/02/2012 11:21 PM
    Edited by: Enyix on 26/02/2012 11:22 PM

    Hello odie_63, thanks for your reply:
    Reasons why needed single tags are these two next: Needed to generate a single XML file from 50,000,000 rows, where the XML ouput matches not only row data but another default values for another elements and attributes (not from database but using strings and types with default values); by using start and end tag, the generated file is as much twice bigger than using single tags; second, needed a very precise presentation for all the document.
    For generating that document, currently focus is based on using a batch process relying on Spring Batch with using a single JDBC query where a join happens between two tables. From my point of view, that approach uses: database resources, network resources, disk resources, and processing resources, including the price of making the join, sending to network, creating objects, validating, and making the file (Expending too much time generating that XML file). That processs currently is in development.
    I think possibly another approach is delegating the complete generation of that file to the database using its XML capabilities. My current approach following your recomendations is to generate a clob where I will put all the XML and putting it into a table. It leads me to another issues: Considering limitations on memory, processing and disk space, needed to append a single row-as-xml into the clob as soon as possible, and putting the clob inside the field as soon as possible, or putting the clob inside the field, and appending into it as the data is generated; so How do I manage the process in order to achieve that goals?. Seen these issues aren't related to my original question, so I'll open a new post. Any help will be apreciated.
    Thanks again in advance.

  • Display as text based on pl/sql - how to return value

    Hi,
    I have a item set as "display as text based on pl/sql". How do I get the PL/SQL anonymous block to return the value of the item?
    My function declares and populates a variable called t_output which is the value I want displayed in the item. The PL/SQL I have written is correct as I have tried it in SQLPlus* with DBMS_OUTPUT.PUT_LINE and I get the correct output, but I don't know how to set my item to the value of t_output. I have tried adding ":P73_ITEM := t_output;" into the end of the PL/SQL block.
    Thanks
    Lucy

    Hi Lucy,
    Try this and see.
    make the display as:display as text(saves state)
    source type: sql query
    in source value or expression type
    select func(arguments) from table name;
    Good luck

  • How to set query SQL on db throug item value?

    Hi
    I've two pages:
    the first page contain the item textfield value (P1_NAME) and second page contain the query SQL.
    Where the query sql instruction insert in the second page rendering?
    In the Items, in the buttons, in the computation, in the process?
    How display the results of query?
    Help Me!!!

    On re-reading I think I get it. When you open the second page, which could be anywhere, you'll have to tell me (could be a Branch, could be a linked column in a report, could be triggered from a button). Whervever the code that opens the second page is, you will see a setting labelled "Target is a" and the chosen selection will be "Page in this Appication" Right under that, you will see two other fields labelled "Set These Items" and "With These Values" this will let you set whatever items you wish on the page that you are opening.

  • How to pass values and see outout of PL/SQL Tables, SYS_REFCURSORs?

    I am new to SQL Developer (Version 3.0.02).
    Our QC division wants to test stored procedures using SQL Developer.
    I tried to test procedures with PL/SQL tables and SYS_REFCURSORS as input and output parameters.
    When we run it by pressing the green arrow we get the Run PL/SQL window.
    How can we:
    - Put values to SYS_REFCURSOR and PL/SQL table type input parameters?
    - How can we display SYS_REFCURSOR and PL/SQL table type output parameters?
    All this time we were using SQL*Navigator. In Navigator the PL Tables and SYS_REFCURSORs outputs are shown in a nice grid.
    Here, in SQL Developer, do we have to WRITE our own code to input and display these types of parameters????

    Hi Channa,
    Yes in SQL Developer 3.0 you will have to write your own code to test out ref cursors.
    I had created test harness scripts for all my procedures having ref cursors as parameters.
    And I had to dbms_output all the values on the screen.
    Probably a limitation of the SQL Developer 3.0 tool.
    In case you come across different solution to this do let me know also.
    Thanks,
    Viju
    blog: http://whizdba.wordpress.com

  • How do count how many 'A' s in this string using sql stmt?

    hi all,
    i have a string like 'AAAAARAMAAAAKRISHNAAAA'.
    in this ,i want to find out how many 'A's .
    how do find out this using select stmt.

    (length(s) - nvl(length(replace(s, 'A')), 0)) / length('A')but consider (by modifying the question slightly to "how do count how many 'AA' s in this string using sql stmt? ")
    SQL>  select (length('AAAAARAMAAAAKRISHNAAAA') - nvl(length(replace('AAAAARAMAAAAKRISHNAAAA', 'AA')), 0)) / length('AA') x from dual
             X
             6
    1 row selected.couldn't I argue that the result should be 10 as e.g. in
    SQL>  select * from xmltable('let $str := "AAAAARAMAAAAKRISHNAAAA"
                            let $search := "AA"
                            for $i in 1 to string-length($str)
                              where substring($str, $i, string-length($search)) = $search
                              return substring($str, $i, string-length($search))' columns x varchar2(10) path '.')
    X        
    AA       
    AA       
    AA       
    AA       
    AA       
    AA       
    AA       
    AA       
    AA       
    AA       
    10 rows selected.Matter of definition I suppose .... ;)
    btw. regexp_count also yields 6:
    SQL>  select regexp_count('AAAAARAMAAAAKRISHNAAAA', 'AA') x from dual
             X
             6
    1 row selected.

  • How to select values frm table giving the condition value at runtime in SQL

    Hi All,
    How to select values from a table by giving the condition value at runtime in SQL
    My SQL statement is select * from employee where empno=<empno>, this empno I want to provide at run time. Also I don't have any bind variables defined. Can anyone please tell how can I achieve this. Also do I have to write a SQL or pl/sql statement.

    Hi Roshni Shankar,
    You can use substitution variable in case of SQL.
    SQL> select * from employees where emplployee_id = &emp_id;
    Enter value for emp_id: 100
    old   1: select * from employees where emplployee_id = &emp_id
    new   1: select * from employees where emplployee_id = 100If you want to put condition on varchar values then eighter provide values in single quotes or use single quote for substitution variable.
    SQL> select * from employees where last_name = &emp_name;
    Enter value for emp_name: 'King'
    old   1: select * from employees where last_name = &emp_name
    new   1: select * from employees where last_name = 'King'
    no rows selected
    SQL> select * from employees where last_name = '&e_name';
    Enter value for e_name: King
    old   1: select * from employees where last_name = '&e_name'
    new   1: select * from employees where last_name = 'King'In case of pl/sql you can pass values to procedure and you can use those values at run time.
    create or replace procedure test (p_emp_id number)
    as
       v_last_name      varchar2(100);
    begin
       select last_name
       into    v_last_name
       from  employees
       where employee_id = p_emp_id;
       dbms_output.put_line(p_emp_id ||'    ->    '||v_last_name);
    end;
    show errors
    SQL>exec test(100);
    SQL>exec test(101);Edited by: Gaurav Bhide on Oct 29, 2012 4:07 AM

Maybe you are looking for

  • Got a MacBook Pro 13' (2011) that keeps crashing occasionally

    I purchased this MacBook Pro early at 2011 and fully upgraded it including extended RAM. The Mac works great most of the time but occasionaly it crashes with no apparent reason. I have no idea if this is a software problem or a hardware malfunction o

  • IFrame in a PopUp

    Hi, I have a component, that I use as a PopUp. Inside this component I have an iFrame. If I call the PopUp it opens and the url I want to load open up in a new Browserwindow and not inside the IFrame. Could this be bacause of a wrong reference to the

  • What content will I loose if I restore my phone from backup?

    I need to restore my iPhone4S from a backup, but I am scared that I will loose photos and videos. Is it guarenteed that everything will be brought back?

  • Presto & Netflix

    We have an excellent opportunity to compare, and we have never had so much choice. Lets face it FTA TV is  the pits at the moment. Prime/Seven, instead of having different programs on their channels, often just shows the same thing on most of it's st

  • When will iBooks Author be available for iPad?

    I read on apple.com in early July that we will be able to create iBooks on the iPad, I was wondering when this will be available, or if it already is.