Summing 2D Array by Columns

Im trying to sum a 2D array by column
Say I have 5 rows and 5 columns im trying to get the sum of all the values in the second column.
What I have so far and have been hassling with for a while is:
public static float sumCol(int[][] table, int rowsize, int colsize)
      int[] c = new int[colsize];
      float sum=0;
      for (int row=0; row < rowsize; row++)
        for (int col=0; col < colsize; col++)
            c[col] = table [row][col];
            sum = myMethods.sum(c);
      return sum;the sum method calculates the sum of an array
If you can help me and just give me some pointers on how to get this, 2D arrays I think play tricks on your mind.

I dont understand why this is giving an out of bounds
when i call it
public static float sumCol(int[][] table, int
rowsize, int colsize)
int[] c = new int[colsize];
float sum=0;
for (int row=0; row < rowsize; row++)
c[row] = table [row][colsize];
sum = myMethods.sum(c);
return sum;
Because number of columns is not the same as number of rows.
I still don't understand why you are creating an array. You don't need one.
Kaj

Similar Messages

  • Can I get multiple sums in a single column based on a "code" I place.

    After importing a file of check/debit card activity from my bank, can I 'code' the line items based on tax categories ie Utilities, Medical expenses, Auto expenses, etc. and then get sums for each based on that code I placed in a single column? That would mean multiple sums in a single column based on the code used for each tax related expense. For instance, I would put UT in the column for utilities expenses and MED in the same column if it were a medical expense. I would then want the sum for all items in that column for each item code. Is this possible or do I need to use a different approach to get this information.

    My guess is that the SUMIF function may be your friend.
    It's well described in the *iWork Formulas and Functions User Guid*e which every user may download from the Help menu.
    Yvan KOENIG (VALLAURIS, France) samedi 2 janvier 2010 21:56:39

  • I use Function Sum to add a column and a new column pops up filled with 0s

    In one of my spreadsheets, every time I try to add a column of numbers using the Sum Function, a new column is added filled with 0s. What's happening? And How do I get it to just add the column?

    can't you just write an SQL script to update the new column?
    Perhaps you can use the integration_id for this? or just another column(s)..

  • Table -- sum of rows and columns?

    I was wondering if anyone has a suggestion to how I can easily generate the sum of each row and column in a two dimensional table? This is what I've got so far:
    public class SumRowsColumns {
        public static void main (String[] args) {
         int[][] table = new int[2][3];
         // gets the values
         for (int i = 0; i < table.length;
              i++) {
             for (int j = 0; j < table.length;
              j++)
              table[i][j] = Terminal.lesInt(); // Terminal is a class that can read the terminal input
         System.out.println("\t\t\t\tSum:");
         // prints the values
         for (int i = 0; i < table.length;
         i++) {
         for (int j = 0; j < table[i].length;
              j++) {
              System.out.print("\t" + table[i][j]);
         System.out.println();
         // sum of first column
         int sumColumn = 0;
         for (int i = 0; i < table.length;
         i++) {
              sumColumn += table[i][0];
         System.out.print("\nSum:\t");
         System.out.println(sumColumn);
    Example of output:
    1
    2
    3
    4
    5
    6
                                    Sum:
            1       2       3
            4       5       6
    Sum:    5This is the output I'd like:
    1
    2
    3
    4
    5
    6
                                    Sum:
            1       2       3     6
            4       5       6     15
    Sum:    5     7     9One way of getting the sum for all the columns is to make a for-loop for each one of them, but there has to be a better way. I could apply the same hack to get the sum of the rows, but I still wouldn't know how to get the layout I want.

    After many hours of frustration I finally solved it (for-loops can be confusing, man) after I got a hint from a post in another forum: http://www.linuxquestions.org/questions/showthread.php?postid=624021#post624021
    A more logical name to the integers actually helped a lot too. And here's the final product:
    public class SumRowsColumns {
        public static void main (String[] args) {
         int[][] table = new int[2][3];
         // gets the values
         for (int row = 0; row < table.length;
              row++) {
             for (int col = 0; col < table[row].length;
               col++)
              table[row][col] = Terminal.lesInt(); // Terminal is a class that reads the terminal input
         System.out.println("\t\t\t\tSum:");
         // prints the values and sum of each row
         for (int row = 0; row < table.length;
              row++) {
             for (int col = 0; col < table[row].length;
               col++) {
              System.out.print("\t" + table[row][col]);
             int sum = 0;
             for (int col = 0; col < table[0].length;
               col++) {
              sum += table[row][col];
             System.out.println("\t" + sum);
         System.out.print("\nSum:");
         // sum of each column
         for (int col = 0; col < table[0].length; // table[0].length is the length of row 0 (the number of columns)
              col++) {
             int sum = 0;
             for (int row = 0; row < table.length; // table.length is the number of rows
               row++) {
              sum += table[row][col];
             System.out.print("\t" + sum);
         System.out.println();
    }

  • Sum of Calculated(Multiplication) Column

    I have a requirement where I need sum of calculated column.
    There are 3 columns.
    A, B and A*B.
    I want the Sum for the 3rd column.
    Sum(A) and Sum(B) are straightforward.
    My question is, how to do the Sum for the thrid column A*B
    Sum(A) * Sum(B) won't give the right value. It will work fine for Addition and Subtraction but not for Multiplication.
    Any help is greatly appreciated.

    Ravi,
    Thanks for the help. It was good one.
    If anyone else intersted to know what he did.
    <?xdoxslt:set_variable($_XDOCTX, ’TVar’, xdoxslt:get_variable($_XDOCTX,’TVar’) + A*B)?>
    and in the group total column print the variable.
    <?xdoxslt:get_variable($_XDOCTX, ’TVar’)?>
    Ganesh

  • Summing the Rows and Columns in an Array

    I am importing a 2-dimensional array of integers.(which is held in a 2-dimensional array)
    I need to store the row sums and column sums in separate 1-dimensional arrays.
    I can get the integers in and print out a list along with the grand total(sum of all).
    But, how do I pass each row's and each column's value in to my sumRow and sumCol methods to get the sum for each row and each column?
    Can I do the row and column summing in the same "for" statement where I calculate the "grand total"? Or am I making this more difficult than it is?
    Would appreciate any help.
    This is what I have so far:
    import java.awt.Graphics;
    import java.applet.Applet;
    public class TwoWayTable extends Applet {
         int numRows;
         int numCols;
         int [] [] cell;
         int [] rowSum;
         int [] colSum;
         int grandTotal;
    public TwoWayTable(int [][] data){
    grandTotal = 0;
    cell = new int [data.length][data.length];
    for(int i = 0; i < data.length; i++)
    for(int j = 0; j < data.length; j++){
         cell[i][j] = data[i][j];
    grandTotal += cell[i][j];
         System.out.println(cell[i][j]);
    System.out.println(grandTotal);
    public int sumRow(int [] data2){
         int rowaccumulator=0;
         rowSum = new int[data2.length];
         for(int numRows = 0; numRows < rowSum.length; numRows++){
         rowaccumulator += rowaccumulator + rowSum[numRows];
              return(rowaccumulator);
    public int sumCol(int [] data3){
         int colaccumulator = 0;
         colSum = new int[data3.length];
         for(int numCols = 0; numCols < colSum.length; numCols++){
              colaccumulator += colaccumulator + colSum[numCols];
              return(colaccumulator);

    Thanks for your input.
    I'll make the changes that you suggest.(after this)
    My output prints:
    4 6 3 8 21
    9 1 5 3 18
    13 7 8 11 39
    numbers are right, but I need to format the table
    the output needs to look like this:
    int int int int | rowsum
    int int int int | rowsum
    colsum colsum colsum colsum | total
    How do I do this?
    I have no idea?
    I'm supposed to call a "void setMargins( )" method to line this up, without
    using the exotic formatting in the IO library.
    I'm also supposed to use "public String toString( )"
    This is what I have so far:
    import java.awt.Graphics;
    import java.applet.Applet;
    public class TwoWayTable extends Applet {
    int numRows;
         int numCols;
         int [] [] cell;
         int [] rowSum;
         int [] colSum;
         int grandTotal;
    public TwoWayTable(int [][] data){
    cell = new int [data.length][data.length];     
    for(int i = 0; i < data.length; i++){
    for(int j = 0; j < data.length; j++){
         cell[i][j] = data[i][j];
    calcTotals(cell);
    for(int i = 0; i < cell.length; ++i){
    for(int j = 0; j < cell.length; ++j){
    System.out.print(cell[i][j] + " ");
    System.out.println(rowSum[i] + " ");
    for(int j = 0; j < cell.length-1; ++j){
    System.out.print(colSum[j] + " ");
    System.out.println(colSum[cell.length-1] + " " + (grandTotal));
         public void calcTotals(int [][] data2){
              grandTotal = 0;
              rowSum = new int[data2.length];                         
              colSum = new int[data2.length];                         
              for(int numRows = 0; numRows < data2.length; numRows++){
              for(int numCols = 0; numCols < data2.length; numCols++){
                   grandTotal += data2[numRows][numCols];               
                   rowSum[numRows] += data2[numRows][numCols];
                   colSum[numCols] += data2[numRows][numCols];

  • Sum 2d arrays with different columns width

    hi,
    I have a 2d array that stores the number of rats in X number of houses.
    in each row, i have the number of rats per house (length) and the weight of each.
    So, if I have 3 houses, I would 3 rows (0,1,2).
    And, in house 1: I have 2 rats (0,1)
    then, rat1 weights 20, rat2: 15
    in house 2: I have 3 rats (0,1,2)
    rat1: 30, rat2: 25 rat3: 5
    in house 3: I have 1 rat (0)
    rat1: 50
    So, what I need to do is to calculate the total weight of rats per house and display:
    Total weight in House1: 35
    House2: 60
    House3: 50
    I dont know how to do the sum and display the sum for each house. Any hints/solutions?
    Message was edited by:
    gixty
    Message was edited by:
    gixty

    > yeah, but I am still looking for a way to sum every
    column per row.
    You've been given the same solution on two different forums. If you know how to loop through the houses, you know how to loop through the rats. The "rat loop" will be nested inside the "house loop". Each rat will be identified by two indices; the house index and the rat index. Just loop through the rats, adding each rat's weight to the total for that house.
    ~

  • How to find the maximum of group sums within a specific column using report builder 3.0

    Hi
    For each part number I am trying to find out in which week of a month did the largest daily shipment occur... so using report builder 3.0
    in SSRS 2012 I can find daily, weekly and monthly totals for the units shipped but I am having a hard time thinking through the logic to find the daily max for each week.
    in my data I can have multiple orders/shipments for the same product on the same day.
    The ultimate goal is to set inventory levels
    So..
    In my matrix report I have
    Row groups:
    Classid => Product class
    InvtID => Item Part Number
    Column Groups:
    FiscYr=> Fiscal Year
    PerPost => Month or period the transaction occurred
    Week_period => the week the transaction occurred
    Day_period => The day that the transaction occurred
    The aggregations are 
    Sum(case_shipped) 
    Max(case_shipped)
    The Sum(case_shipped) is working as desired but the Max(case_shipped) is picking out the max amount shipped on any one order when looking
    at the week, month or fiscal period and that is not what I need.
    I have attached a screenshot since a picture is worth more than my words. I have also included some sample data
    I would very much appreciate any thoughts on this. I am guessing that the solution has something to do with using the inscope function but
    I can't wrap my head around how to use it
    Thank you 
    Tom D
    Here is some sample data for Product A
    Invtid Case_ship Trandate    FiscYr   PerPost   week_period        day_period
    A         10           1/1/2104    2014        1    
              1                           1
    A           3           1/1/2014    2014        1  
                1                           1
    A         50           1/2/2104    2014        1    
              1                           2
    A         30           1/3/2014    2014        1    
              1                           3
    A         20           1/9/2104    2014        1    
              2                           2
    A          5            1/9/2104    2014        1  
                2                           2
    A        20          1/10/2014    2014        1    
              2                           3
    A        60          1/10/2104    2014        1    
              2                           3
    On 1/1/2104 I shipped a total of 13 cases
    On 1/2/2104 I shipped a total of 50 cases
    On 1/3/2104 I shipped a total of 30 cases
    On 1/9/2014 I shipped a total of 30 cases
    On 1/10/2014 I shipped a total of 80 cases
    On 1/9 I shipped a total of 25 cases
    I would like to show that in week 1 the maximum number of cases shipped on any day is 50 (1/2/2014)
    I would like to show that in week 2 the maximum number of cases shipped on any day is 80 (1/10/2104)
    I would also like to show that in perpost (month) 1 the maximum
    number of cases shipped on any day is 80 (1/10/2104)

    Hi
    I was able to find a solution
    I built a new dataset in report builder using the same table as before but tried out the "Group and Aggregate" function and for the case_ship
    field I chose "Sum" as my aggregate.... In essence this gave me a very cool and easy daliy sum of the shipped cases. 
    When I used this new dataset and built my matrix report I was able to easily get the max daily shipment for each product by week, month and
    year.
    Tom

  • Place a SUM of a selected column in an EASY CALENDAR region

    Hello,
    I'd like to SUM a particular field (SCHEDULE_TABLE.SCHEDULE_PERCENT_FORECAST)
    And place it in EASY CALENDAR. The idea is that if a resource had 3 records in the SCHEDULE_TABLE for a given date, the sum of the 3 SCHEDULE_PERCENT_FORECAST fields would appear as a Display Value inside the cell of EASY CALENDAR.
    I'm having trouble making this happen.
    What I've tried thus far is to create an Item in the calendar region and called it: P2_RESOURCEPERCENTSCHEDULED. In that Item, I took a shot at the SQL for the "Source Value Or Expression" and made the source type = "PL/SQL or Expression or Function" The SQL currently reads:
    select     sum(SCHEDULE_TABLE.SCHEDULE_PERCENT_FORECAST) as "SCHEDULE_PERCENT_FORECAST"
    from     "SCHEDULE_TABLE" "SCHEDULE_TABLE"
    where      "SCHEDULE_TABLE"."RESOURCE_ID" = P2_RESOURCE_ID
    and     "SCHEDULE_TABLE"."THE_DATE" = 11-JAN-08
    group by SCHEDULE_TABLE.SCHEDULE_PERCENT_FORECAST
    The field P2_RESOURCE_ID is from another region of the page where the user has previously selected the Resource.
    The field SCHEDULE_TABLE.THE_DATE is date field from the schedule table which should correspond to the date field in EASY CALENDAR. I used the value of 11-JAN-08 because I know I have 3 records for that date. I know the final SQL shouldn't look like that, but I didn't know how the SQL should look so that it would SUM for each date in the calendar.
    I hope this explains the issue well enough. I appeciate your help.
    Phil

    Hello,
    I discovered a big portion of my problem is that I wasn't adjusting the Region Source to identify the fields I needed for the calendar. My problem now is the construction of my SQL. Here's where it stands now.
    DECLARE
    Temp_Resource_ID NUMBER;
    BEGIN
    Temp_Resource_ID := P2_RESOURCE_ID;
    select SUM("SCHEDULE_TABLE"."SCHEDULE_PERCENT_FORECAST")
    as "SCHEDULE_PERCENT_FORECAST",
    "SCHEDULE_TABLE"."THE_DATE" as "THE_DATE",
    "SCHEDULE_TABLE"."RESOURCE_ID" as "RESOURCE_ID"
    from "SCHEDULE_TABLE" "SCHEDULE_TABLE"
    where "RESOURCE_ID" = "Temp_Resource_ID"
    group by "SCHEDULE_TABLE"."SCHEDULE_PERCENT_FORECAST";
    END;
    P2_RESOURCE_ID is an item from another region on the page where the user would have selected the Resource to view in the calendar.
    Temp_Resource_ID is a temporary field for use within the SQL
    The other fields are existing fields within the database
    The error I get is:
    1 error has occurred
    Query cannot be parsed, please check the syntax of your query. (ORA-06550: line 1, column 8: PLS-00103: Encountered the symbol "" when expecting one of the following: begin function package pragma procedure subtype type use form current cursor)
    Yet this general format of SQL seems to work in the SQL COMMANDS section of SQL WORKSHOP. Please let me know what I'm doing wrong.
    Thanks again for your help.

  • SUM function for a column made 'on the fly'

    I have access to a database, however only SELECT statements can be run on the database. Basically the database lists switches, these switches can have up to 20 computers connected to them but some do not. I need to know the switches which contail less than 20 computers so I know where there is space for more computers (I've wrote the code for this already). I also need something to keep a tally/total for the number of spare spaces left so I can run the script and go 'ok we have a total of 20 spare places for computers theres 10 on this switch and 10 on this one'.
    I just need to get the sum funtion working for the column that I've created 'on the fly', the column revealing the number of spare slots, heres the code I've got so far:
    SELECT switch, COUNT(*) as "Servers", 20 - COUNT(*) as "Spare slots"
    from dedicated_servers
    where switch like 'rs%'
    GROUP by switch
    HAVING COUNT(switch) < 20
    order by Servers;
    Which gives the following:
    | switch | Servers | Spare slots |
    | rsj14-1.dc | 12 | 8 |
    | rsj12-1.dc | 15 | 5 |
    | rsi2-2.dc | 16 | 4 |
    | rsj13-1.dc | 16 | 4 |
    | rsi2-1.dc | 16 | 4 |
    Just need something at the end saying TOTAL=25

    OK I'll have to make em up though, but they are something like this for one switch:
    INSERT INTO dedicated_servers (switch, server_number, switch_socket)
    VALUES (rsj-1.dc, 100, 18)
    On switch rsj-1.dc there can be upto 20 servers (the server_number is the primary key)
    Message was edited by:
    slowpoke115

  • Chcing the sum option on a column not working

    The 3 columns titled Total_25_Probability, Total_50_Probability,Total_90_Probability are not totaling although I have checked the sum option in the report attributes. Any ideas?
    Here's the query that forms the table:
    Select REGION , FIRST_APPOINTMENTS ,PROSPECTS_25 , TOTAL_25_REVENUE , TOTAL_25_PROBABILITY , PROSPECTS_50 ,TOTAL_50_REVENUE , TOTAL_50_PROBABILITY , NUM_90_PROSPECTS , TOTAL_90_REVENUE , TOTAL_90_PROBABILITY , CURRENT_MTH_CLOSES , CURRENT_MTH_BOOKED_REV , YTD_CLOSED , YTD_CLOSED_REV ,(Total_90_Probability + Total_50_Probability + Total_25_Probability) as SixtyDayOutlook
    from (SELECT OFFICE_ID as Region,
    Count (CASE WHEN v.STATUS = 'FA' then
    v. prospect_id
    else 0
    end) as First_Appointments ,
    Count (CASE WHEN v.STATUS = '25%' then
    v. prospect_id
    else 0
    end) as PROSPECTS_25 ,
    sum (CASE WHEN v.STATUS = '25%' then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) as Total_25_Revenue ,
    to_char( (sum (CASE WHEN v.STATUS = '25%' then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) *.25 ), '99999999999999999') as Total_25_Probability ,
    Count (CASE WHEN v.STATUS = '50%' then
    v. prospect_id
    else 0
    end) as PROSPECTS_50 ,
    sum (CASE WHEN v.STATUS = '50%' then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) as Total_50_Revenue ,
    to_char( (sum (CASE WHEN v.STATUS = '50%' then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) *.50 ), '99999999999999999') as Total_50_Probability ,
    Count (CASE WHEN v.STATUS = '90%' then
    v. prospect_id
    else 0
    end) as NUM_90_PROSPECTS ,
    sum (CASE WHEN v.STATUS = '90%' then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) as Total_90_Revenue ,
    to_char((sum (CASE WHEN v.STATUS = '90%' then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) *.90 ), '99999999999999999') as Total_90_Probability ,
    count (CASE WHEN v.STATUS = 'Closed' and to_char(target_close_date , 'Mon') = to_char(target_close_date,'Mon') then
    v. prospect_id
    else 0
    end) as Current_Mth_Closes ,
    sum (CASE WHEN v.STATUS = 'Closed' and to_char(target_close_date , 'Mon') = to_char(target_close_date,'Mon') then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) as Current_Mth_Booked_Rev ,
    count (CASE WHEN v.STATUS = 'Closed' and to_char(target_close_date - 1 , 'YEAR') = to_char(sysdate ,'YEAR') then
    v. prospect_id
    else 0
    end) as YTD_Closed ,
    sum (CASE WHEN v.STATUS = 'Closed' and to_char(target_close_date -1 , 'YEAR') = to_char(target_close_date,'YEAR') then
    nvl(EST_ANNUAL_REVENUE, EST_INCREMENTAL_REVENUE)
    else 0
    end) as YTD_Closed_Rev
    from vms_prospects v join VMS_PROSPECTING_ITEMS i
    on v.prospect_id = i.prospect_id
    where i.active = 'Y'
    group by OFFICE_ID)

    never...I see that I converted those columns into chars. For some reason to_number was throwing an error. I suppose I need to take this to the pl/sql forum.

  • SUM on GO URL column

    Guys,
    I Have 2 reports .. Master & Details.. Sources of these 2 reports are different .. so i used GO URL to link them.
    I had SUM(COL1) for which i need Navigate .. by CAST(NUMBER AS CHAR) i could enable that...
    With out converting it to char.. i am facing error in defining the GO URL link.. i am getting error stating.. "Concat does not work with non-text type columns.... bla bla bla........."
    so i user CAST() and achieved the requirement.... till now it is fine...
    But now the user wants CHART for the Master Report.. when i am creating chart view... its throwing an error when i include the SUM() column in the chart...., of course it should as i am creating Chart on a CHAR column.
    Somehow i should achieve.. when the user click on the BAR/LINE of the chart.. i shuld be able to go go to the detail report....
    Is this possible....?
    Please let me know if i am not clear?
    Thanks
    Kiran

    Kiran,
    I tired out a similar example and ended up with the same error.
    It works fine with table view but not with chart view.
    Upon further research found this note. Maybe useful for you:
    Users can't drill or navigate because their results are in different tables. This could be addressed in the rpd. A primary purpose of this layer is to bring together different sources of data into a single unit so that they can be addressed as if they were a single source.
    So, I suggest you to make changes in rpd and make these sources as single source and do a normal navigate.

  • Function Sum of Characters in Columns, If statements

    This one is a doozy, I think. At least, I've never heard of it being needed in this way.
    The Mission
    To turn Hootsuite’s bulk uploader into an even better Twitter tool by checking the lengths of tweets before they are uploaded.
    The Question
    How can I check if the SUM of Columns B and C, Tweet and Hyperlink, respectively, exceeds 140 characters, even after Twitter shortens the Hyperlink?
    NOTE: The Date/Time won't matter, as it is
    only used for Scheduling purposes.
    This is kind of as far as I have come. I know that there is a COUNTIF function, but I'm not sure if that will do the trick.
    I would also like it to show in Column D (Cleared), if the tweet exceeds 140 characters, by how many.
    A gold star to anyone who can figure this out. I will be sharing the file online for anyone who uses Hootsuite to schedule tweets, as well, so think of this as a charity event.

    Here's an alternate formula, and a solution which includes your request, "I would also like it to show in Column D (Cleared), if the tweet exceeds 140 characters, by how many."
    (Click image for larger, more readable version.)
    =LEN(B)+MIN(LEN(C),20)-140
    LEN(B) returns the number of characters in B.
    MIN(LEN(C),20) returns the number of characters in the link in C if that is 20 or fewer, and returns 20 if the link will be shortened by bit.ly.
    Subtracting 140 tells the number of characters still available (if negative or zero) or the number of excess characters (if positive).
    The conditional format rules (applied to all cells in column D) call attention to overlong tweets by changing the fill colour to red, the text colour to yellow, and making the text bold. The second rule applies a green fill to the cell if the tweet is within the 140 character limit.
    Regards,
    Barry

  • Splitting up sum function into 2 columns

    There are only 2 possible values for t1_type (1 or 2)
    create table t1 (id number, t1_type number, amount number);
    insert into t1 values (1,1,5);
    insert into t1 values (1,1,10);
    insert into t1 values (1,2,35);
    insert into t1 values (1,2,20);
    insert into t1 values (2,1,5);
    insert into t1 values (2,1,10);
    insert into t1 values (2,2,35);
    insert into t1 values (2,2,20);
    for each id I require an sql statement to return exactly one row with 3 columns,
    id, sum(amount) /*for t1_type 1*/,sum(amount)/*for t1_type 2*/
    Desired output from above data would be:
    1,15,55
    2,15,55
    Thanks
    Sam.

    Is this you wanted?
    sql>
    select id,sum(decode(type,1,amt,0)) sum_type1,sum(decode(type,2,amt,0)) sum_type2
    from t1
    group by id;
    ID SUM_TYPE1 SUM_TYPE2 
    1  15  55 
    2  15  55
    jeneesh                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Sum calculated rows and columns

    I have written a SQL report to count the number of offenses by levels of disciplinary actions.  Now I want to total
    the counts for the rows and columns.  How do I do this? Below is my code.  It produces column headings with counts.  Ie.
    Offense Description   Level I  Level II  Susps Terms
    2 Minor Violations      0         1       
    0    0  
    SELECT
    UPPER(DESCRIPTION) as OFFENSE,
    SUM(CASE
    WHEN OUTCOME = 'LEVEL I'
    THEN 1
    ELSE 0
    END) as LEVELI,
    SUM(CASE
    WHEN OUTCOME = 'LEVEL II'
    THEN 1
    ELSE 0
    END) as LEVELII,
    SUM(CASE
    WHEN OUTCOME = 'SUSPEND'
    THEN 1
    ELSE 0
    END) as SUSPEND,
    SUM(CASE
    WHEN OUTCOME = 'TERM'
    THEN 1
    ELSE 0
    END) as TERM
    FROM
    PAGRDI
    Where
    R_DATE >= '2014-01-01' and R_DATE <= '2014-01-31'
    Group by
    DESCRIPTION
    Order by
    OFFENSE

    Hi Wildcatgirl,
    According to your description, you have used T-SQL to get the counts for different OUTCOME. Now you want to get the total for each OFFENSE and OUTCOME. Right?
    In this scenario, since you have already get those counts with T-SQL query, so in your dataset it will have data fields below: OFFENSE, LevelI, LevelII, SUSPEND, TERM. We just need to drag these data fields into a table, add a column at the end of the table
    and use expression to sum the counts for different OUTCOME. Then we can add a total for the detail row. We have tested this scenario in our local environment. Here are screenshots for your reference:
    Reference:
    Tables (Report Builder and SSRS)
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou

Maybe you are looking for