Selecting on a Max Count of rows

I would like some advice on the following SQL. I am trying to select the max(count(*)) of a selct count(*). (if you know what I mean??)
select district_id
from (
     -- retrieve a list of districts, plus the count of employee related records
     select d.district_id, count(*) CountX
     from station s, division d
     where s.resp_empl_num = :empID and
     s.stn_status_code = 'AC' and
     s.resp_div_num = d.division_code
     group by d.district_id
     -- match on the district with the max count #
where CountX = (
     select max(count(*))
     from station st, division dv
     where st.resp_empl_num = :empID and
     st.stn_status_code = 'AC' and
     st.resp_div_num = dv.division_code
     group by dv.district_id
)

Try this
select district_id
from ( select district_id,
              rank() over (order by count(*) desc) rn
       from   station s, division d
       where  s.resp_empl_num = :empID and
              s.stn_status_code = 'AC' and
              s.resp_div_num = d.division_code
       group by d.district_id
) where rn=1
;

Similar Messages

  • Howto limit max. count of rows in a TABLES-based import-parameter?

    Hello all,
    I have created a web service based on a custom function module in SAP. Beside others this function module provides one TABLES input parameter, which is set to "optional". Now I want to publish the web service with this parameter optionally as well, but also allow it for max. 10 tmes (meaning max. 10 rows for this import table).
    I have found an entry for min and max settings in SE80 for this web service, but unfortunately these both fields are read-only, so I can't set the maxOccurs here.
    Any ideas how I can solve this problem?
    Thanks in advance for your help!
    Kind regards, Matthias
    Edited by: Matthias F. Brandstetter on Oct 21, 2010 10:32 AM

    Hi,
    It is not possible to change SAP generated service. Better you create new service in ESR and assign correct maxOccurs and then create proxy of this service in backend where you can also map ESR service to FM.
    To minimize effort you can copy same wsdl and then change wsdl and import in ESR as new service.
    Regards,
    Gourav

  • Issue returning a count of rows in a SELECT QUERY...

    I am working in Oracle 11.2g and I have a query where I want to return the count of DAILY records as well as WEEKLY records for specific marketers.
    Here is my query:
    Select     Mka_Mktr_No, 
              Case When Rat_Freq_Cd = 'D' Then Count(*) Else 0 End DailyCount,
              case when Rat_Freq_Cd = 'W' then count(*) Else 0 End WeeklyCount
            From     Marketer_Account, Acct
            Where     Mka_Exp_Dt >= '01-NOV-2012'
            And     Mka_Eff_Dt <= '30-NOV-2012'
            and     rat_acct_no = mka_acct_no
            And     Rat_Usage_Cd = 'P'
            and rat_freq_cd != 'M'
            Group By Mka_Mktr_No, Rat_Freq_Cd
            Order By Mka_Mktr_No;I would prefer to have the results show up on the SAME row, but instead I get the following results:
    MKA_MKTR_NO            DAILYCOUNT             WEEKLYCOUNT           
    10005                  68                     0                     
    10005                  0                      2                      Note how it shows each count on a seperate row. Is there a way to tweak the query to show the counts on the same row:
    MKA_MKTR_NO            DAILYCOUNT             WEEKLYCOUNT           
    10005                  68                     2       and not have two seperate rows?
    Many thanks,
    Sean

    Don't group by rat_freq_cd
    SQL> with test_data as
      2      (
      3      select 1 mka_mktr_no, 'W' rat_freq_cd from dual union all
      4      select 1 mka_mktr_no, 'W' rat_freq_cd from dual union all
      5      select 1 mka_mktr_no, 'D' rat_freq_cd from dual union all
      6      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
      7      select 2 mka_mktr_no, 'W' rat_freq_cd from dual union all
      8      select 2 mka_mktr_no, 'W' rat_freq_cd from dual union all
      9      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
    10      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
    11      select 2 mka_mktr_no, 'D' rat_freq_cd from dual union all
    12      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
    13      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
    14      select 3 mka_mktr_no, 'W' rat_freq_cd from dual union all
    15      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
    16      select 3 mka_mktr_no, 'D' rat_freq_cd from dual union all
    17      select 3 mka_mktr_no, 'W' rat_freq_cd from dual
    18      )
    19  select
    20      mka_mktr_no,
    21      count(case when rat_freq_cd = 'D' then rat_freq_cd end) dailycount,
    22      count(case when rat_freq_cd = 'W' then rat_freq_cd end) weeklycount
    23  from
    24      test_data
    25  group by mka_mktr_no;
    MKA_MKTR_NO DAILYCOUNT WEEKLYCOUNT
              1          1           2
              2          4           2
              3          4           2

  • Count the rows which are selected ?

    Hi Experts,
    I need help.My requirement is:
    I am having a table which can be multiple selected. But there are two buttons attached to it.Edit and Delete.For Delete I want the Multiple Selection not for EDit.So, If i will click the Edit after multiple selection of the rows.How i can give pop-up that multiple edit is not possible?Means I want to count the rows which are selected how to do that?
    Please guide me.
    Urgent need
    Regards
    Nutan

    Hi Nutan,
    Marcel is right about backend. However I might have an idea once I am developing a quiet similar solution. I would like to ask you to explain with more detail. It seems you have two requirements in one question.
    Regards,
    Gilson

  • Pivot min & max in single row.

    Greetings,
    Please help me in this case...
    Can we get the columns as,
    Dimension, # Count, MAX (# Count), MIN (#Count) all in one line with separate values but separate min, max & count in pivot.
    also imagine for multiple rows .
    this report is seen on year level but the min & max shld be on a level below, quarter.
    i.e. this report will give the total count for all quarters, max no of count from 4 quarters & same for min.
    ---------|_--____________YEAR_____________
    Dim ---|# Count -- MAX (Count) --- MIN (Count)
    Please help.
    Thanks,
    Dev

    I'm not sure if this is what you're after, but using Aketi's tabibitosan method:
    with results as (select someid,
                            adate,
                            row_number() over (order by adate) rn,
                            dense_rank() over (partition by someid order by adate) dr,
                            row_number() over (order by adate) - dense_rank() over (partition by someid order by adate) diff
                     from   t1)
    select someid,
           min(adate) min_adate,
           max(adate) max_adate
    from   results
    group by someid, diff
    order by min(adate);
        SOMEID MIN_ADATE                       MAX_ADATE                     
           756 25/01/2010 07:22:57.000000      25/01/2010 07:23:58.000000    
           822 25/01/2010 07:24:44.000000      25/01/2010 07:25:33.000000    
           770 25/01/2010 07:29:53.000000      25/01/2010 07:30:11.000000    
           816 25/01/2010 08:03:02.000000      25/01/2010 08:27:13.000000    
           770 25/01/2010 08:54:04.000000      25/01/2010 08:54:16.000000    
           822 25/01/2010 08:58:07.000000      25/01/2010 08:58:09.000000

  • Combine seperate lookupsets - find max(), count()?

    Hello, my knowledge of SSRS is intermediate.  Enough to have a plan.  But I need just a little assistance.
    Here are the functions.
    here are my three lookupsets:
    -LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value, “AccountActivities”)
    -LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value, “AccountContactActivities”)
    -LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value, “AccountOpportunityActivities”)
    1) How could I find the 'Max()' of all three of these datasets.  The single highest number.
    2) How could I find the 'COUNT()' of all three of these datasets.   The total number of rows.
    If they can be done separately and then added together using variables, that is an acceptable solution.  Still, I'm just learning syntax here.
    THanks

    Hi ebs_software,
    According to your description, you used three lookupset function to retrieve data from other dataset, now you want to select max value and count of values of all three datasets.
    I tested the issue in my local machine, we could not select sum and max value returned by lookupset function directly. To workaround this issue, we need to use custom code. For detail information, please refer to the following document:
      1. Right-click outside of the report, click Report Properties.
      2. Click Code in left pane, type the code like below:
    Public Function AggLookup(ByVal choice as String, ByVal items as Object)
    If items is Nothing then
    Return Nothing
    End If
    Dim current as Decimal
    Dim sum as Decimal
    Dim count as Integer
    Dim min as Decimal
    Dim max as Decimal
    Dim err as String
    current = 0
    sum = 0
    count = 0
    err = ""
    For each item as Object in items
    'Calculate count
    count += 1
    'Check value is a number
    If IsNumeric(item) then
    'Set current
    current = Convert.ToDecimal(item)
    'Calculate sum
    sum += current
    'Calculate min
    If min = Nothing then
    min = current
    End If
    If Min >current then
    min = current
    End If
    'Calculate max
    If max = Nothing then
    max = current
    End If
    If max < current then
    max = current
    End If
    'Return NaN if value is not a number
    Else
    err = "NaN"
    End If
    Next
    'Select and set output based on the user choice or choice passed by function
    If err = "NaN" then
    If choice = "count" then
    Return count
    Else
    Return err
    End If
    Else
    Select Case choice
    Case "sum"
    Return sum
    Case "count"
    Return count
    Case "min"
    Return min
    Case "max"
    Return max
    Case "avg"
    'Calculate the average avoiding divide by zero errors
    If count > 0 then
    Return sum / count
    Else
    Return 0
    End If
    End Select
    End If
    End Function
      3. Right-click handle of the column you want to count values returned by lookupset function, click Expression.
      4. In Expression text box, type the expression like below:
    =LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value,"AccountActivities").Length + LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value,"AccountContactActivities").Length + LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value,"AccountOpportunityActivities").Length
      5. Right-click handle of the column you want to calculate total of values returned by lookupset function, click Expression.
      6. In Expression text box, type the expression like below:
    =Code.AggLookup("sum",LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value,"AccountActivities"))
      7. Right-click handle of the column you want to select max value returned by lookupset function, click Expression.
      8. In Expression text box, type the expression like below:
    =Code.AggLookup("max",LookupSet(Fields!name.Value, Fields!name.Value, Fields!act_actualend.Value,"AccountActivities"))
    The following screenshot is for your reference:
    If you have any more questions, please feel free to ask.
    Thanks,
    Wendy Fu
    If you have any feedback on our support, please click
    here.
    Wendy Fu
    TechNet Community Support

  • Max(count(*))

    countries(country_name, country_id, region_id)
    Employees(employee_id,first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_PCT, manager_id, department_id)
    departments(department_id, location_id, manager_id, department_name)
    job_history(employee_id, start_date, end_date, job_id, department_id)
    jobs(job_id, job_title, min_salary, max_salary)
    locations(location_id, street_address, postal_code, city, state_province, country_id)
    regions(region_id, region_name)
    question is display all countries that are located in the region which has most countries in the countries table
    select country_name
    from countries
    where region_id=1
    --(select max(count(*)) from countries group by region_id)Instead of using 1 where where clause, i need to write a sub query to get the region 1.

    Oficially tested ;) :
    SQL> insert into countries values('France',1,1);
    1 row created.
    SQL> insert into countries values('Italy',2,1);
    1 row created.
    SQL> insert into countries values('China',3,2);
    1 row created.
    SQL> insert into countries values('India',4,2);
    1 row created.
    SQL> insert into countries values('Mongolia',5,2);
    1 row created.
    SQL> select  country_name,
      2          country_id,
      3          region_id
      4    from  countries
      5    where (region_id,1) in (
      6                            select  region_id,
      7                                    dense_rank() over(order by count(*) desc) rnk
      8                              from  countries
      9                              group by region_id
    10                           )
    11  /
    COUNTRY_NAME                   COUNTRY_ID  REGION_ID
    China                                   3          2
    India                                   4          2
    Mongolia                                5          2
    SQL> SY.

  • SQL: Find table with max no. of rows

    I have a table containing list of table names for each owner; as
    ## Table: db_tables
    OWNER TABLE_NAME
    a ta_1
    a ta_2
    a ta_3
    b tb_1
    b tb_2
    c tc_1
    Now, i want to know the table with max. no. of rows for each owner
    Plz....can anyone gimme a solution for the above ......

    Assuming 10g and above:
    SQL>  SELECT owner,
                 MAX(table_name) KEEP (DENSE_RANK FIRST ORDER BY XMLQUERY (t RETURNING CONTENT).getnumberval() DESC) table_name,
                 MAX(XMLQUERY (t RETURNING CONTENT).getnumberval()) cnt
        FROM (SELECT owner,table_name,    'count(ora:view("' || table_name || '"))' t
                FROM all_tables
               WHERE owner IN ('MICHAEL','SCOTT'))
               GROUP BY owner
    OWNER                          TABLE_NAME                            CNT
    MICHAEL                        SERVICE_ZIP                       1000000
    SCOTT                          EMP                                    14
    2 rows selected.

  • Count of rows having different values

    SQL>  select  * from med;
    CERT  REC  PRIM RACE
    100    10   EN   USA
    100    11   EN   USA
    100    12   EN   USA
    100    13   SP   MX
    200    14   SP   MX
    200    15   SP   MX
    6 rows selected.
    SQL>  select  * from sub;
    CERT  REC PRIM RACE
    100    10   EN   USA
    100    11   EN   USA
    100    12   EN   USA
    100    13   SP   MX
    200    14   SP   MX
    200    15
    6 rows selected.
    SQL> select  * from den;
    CERT  REC  PRIM RACE
    100    01   EN   USA
    100    02   EN   USA
    100    03   EN   USA
    100    04   SP   MX
    200    06   SP   MX
    (cert,rec) uniquly identifies a person;
    In Den table rec =med.rec-9 or rec =sub.rec-9 which implies
                med       sub     den
    (cert,rec)=(100,10)=(100,10)=(100,01)How can I find out how many people in the table where the PRIM and RACE hold different values.?

    Hi,
    Perhaps this ,
    with med as (
    select 100 CERT,   10 rec,   'EN' prim,   'USA' race from dual union all
    select 100  ,  11,   'EN',   'USA' from dual union all
    select 100  ,  12,   'EN',   'USA' from dual union all
    select 100  ,  13,   'SP',   'MX' from dual union all
    select 200  ,  14,   'SP',   'MX' from dual union all
    select 200  ,  15,   'SP',   'MX' from dual )
    sub as (
    select 100 CERT,    10 rec ,  'EN' prim,   'USA' race from dual union all
    select 100,    11 ,  'EN',   'USA' from dual union all
    select 100,    12 ,  'EN',   'USA' from dual union all
    select 100,    13 ,  'SP',   'MX' from dual union all
    select 200,    14 ,  'SP',   'MX' from dual union all
    select 200,    15, null, null  from dual )
    den as (
    select 100 cert,    01 rec,   'EN' prim,  'USA' race from dual union all
    select 100,    02,   'EN' ,  'USA'from dual union all
    select 100,    03,   'EN' ,  'USA'from dual union all
    select 100,    04,   'SP' ,  'MX'from dual union all
    select 200,    06,   'SP' ,  'MX'from dual )
    ----- sample data
    select cert, prim, race ,count(rec) rec
    from (
    select *
    from med
    union all
    select *
    from sub
    union all
    select *
    from den
    group by cert, prim, race
    ORDER BY 1,2,3
          CERT PR RAC        REC
           100 EN USA          9
           100 SP MX           3
           200 SP MX           4
           200                 1HTH
    SS

  • Count of rows from different tables.

    Hi Friends,
    I have 4 tables with a common column name "ID". I would like to get the count of rows from all the four tables which has the same ID.
    Ex
    select count(a.id) from table1 a,table2 b,table3 c,table4 d where a.id=b.id=c.id=d.id=5;
    please suggest me some solution

    may be thsi?
    select count(a.id) from table1 a,table2 b,table3 c,table4 d
    where a.id=b.id and a.id=c.id and a.id=d.id and a.id=5;

  • How to get count of rows for a table?

    Hi,
    How to get count of rows for a table and secondly, how can i have access to a particular cell in a table?
    Regards,
    Devashish

    Hi Devashish,
    WdContext.node<Your_node_name>().size() will give you the no: of rows.
    This should be the node that is bound to the table's datasource property.
    WdContext.node<Your_node_name>().get<node_name>ElementAt(index_value); will select the row at that particular index.
    You can access an attribute of a particular row as
    WdContext.node<Your_node_name>().get<node_name>ElementAt(index_value).get<attribute_name>();
    Hope this helps,
    Best Regards,
    Nibu.
    Message was edited by: Nibu Wilson

  • Max no.of rows capacity in a cursor ?

    Gurus,
    Do we have any limitations in cursors to hold max no.of rows returned by a SQL ?
    My select returning 50 Million rows. Can I hold all of them in a single cursor ?
    Thnaks.
    S

    Wrong question. A cursor does not have "capacity".
    A cursor is an executable program. Not a set of results. It is not a copy of resulting rowids/rows for the SQL. Just imagine if it was.. how many cursors could we then open? Each cursor will consume loads of memory as each cursor will need to make a copy of the data. This is not scalable at all. A RDBMS will struggle to support more than just a couple of user sessions.
    Source SQL is in fact a source program. A set of instructions in the SQL language of what the server needs to do. This program is parsed by the SQL Engine and then a binary executable program created for it. This is stored as a shared program (to be used by any session needing it) in the Shared Pool. This is why using bind variables are important (it allows the program to be generic without hardcoded values). The instructions of this binary program can be seen via its execution plan. This binary executable program is commonly called a cursor in database speak.
    A program typically consists of a code segment and a data segment. The code segment is the cursor in the Shared Pool. And this code segment of the program can be used by any other session too.
    When you open the cursor, you access the code segment of the program in the Shared Pool. A data segment is created just for your use of that program. This contains the state variables, bind variable values, and other data required for executing and managing the program. (A DLL in Windows and SO in Unix/Linux, work in the exact same fashion)
    When you fetch from the cursor, the program is executed (as per the execution plan determined by the CBO). Your cursor's state data is updated. And you get, as output from this program, data in the form of rows.
    Each subsequent fetch repeats this process, until the program (cursor) fails to find any more rows to return.
    All SQL statements, every single one, is treated in this fashion. It is parsed and compiled, execution plan determined and then stuffed into the Shared Pool as a cursor. Does not matter if it is a SQL statement from Java, SQL*Plus, Delphi, inside PL/SQL, or a nested SQL generated by Oracle itself.
    How many rows can be returned by a binary executable program (cursor)? You could just as well have asked, how many rows can a source code program (SQL statement) return?
    The answer to that is, how many rows are in the table?
    There is no limit in that regard. What is a limit in this respect, is the size of the redo when running a SQL on a table "slowly", while the table is subject to a lot of changes. The consistent read/view you have on that table (also called a snapshot) needs to be maintained for the duration of that cursor's execution. At some stage that cursor may fail to find the rows matching the version of data required to provide you with a consistent read. In such a case, the cursor will throw an exception saying that the snapshot is now too old and cannot be reconstructed anymore.

  • Count all rows of a Database table

    I want to count all the rows of a table.
    I have made correctly the connection with the database and all the other things (make a statement, make the query and the resultSet), I use the MySQL server v4.0.17
    Here is the code I use:
    int count=0;
    String temp=null;
    String query = "SELECT COUNT(*) FROM customers";//customers is my Database Table
    try {
    rs = stmt.executeQuery(query);
    }//end try
    catch(Exception exc) {
    createFeatures.PlayErrorSound(registerRenter);
    Optionpane.showMessageDialog(registerRenter,
    "MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
    }//end catch
    try {
    while(rs.next()) {
    count++; //I use this variable in order to count the rows because the resultSet doesn't tell me the answer
    countLine=rs.getInt(1);
    }//end while
    }//end try
    catch(Exception exc) {
    createFeatures.PlayErrorSound(registerRenter);
    Optionpane.showMessageDialog(registerRenter,
    "MESSAGE", "ERROR", JOptionPane.ERROR_MESSAGE);
    }//end catch
    count=count++; //i increase it aggain because if the rows are initial 0 i want to make it 1
    temp = String.valueOf(count);//i use this command in order to display the result into a jtextfield
    Any help is appreciated!!!!!

    This program will work just fine against mysql:
    mport java.util.*;
    import java.io.*;
    import java.sql.*;
    public class Test {
    public static void main(String []args) {
    String url= "jdbc:mysql://localhost/adatabase";
    String query = "select count(*) from foo2";
    String createQuery="create table foo2(f1 int)";
    String dropQuery="drop table foo2";
    String insertQuery="insert into foo2 values(1)";
    Properties props = new Properties();
    props.put("user", "auser");
    props.put("password", "xxxxx");
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    System.out.println("Connecting to the msql server");
    Connection con = DriverManager.getConnection(url, props);
    Statement stmt = con.createStatement();
    try {
    stmt.executeUpdate(dropQuery);
    } catch(SQLException e) {}
    stmt.executeUpdate(createQuery);
    stmt.executeUpdate(insertQuery);
    stmt.executeUpdate(insertQuery);
    PreparedStatement pstmt = con.prepareStatement(query);
    System.out.println("***Executing a select");
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
    System.out.println("RowCount="+ rs.getString(1));
    rs.close();
    pstmt.close();
    stmt.close();
    con.close();
    } catch(Exception e) {
    System.out.println(e.getMessage());
    }

  • Count of rows in ALv report

    Hi!
    I would like to get the count of rows in my ALV report . How to get the count of the rows ? Can anyone guide me in getting it dome please.
    Thanks

    Hi Gaddemmedi!
    I am attaching the report as you had asked for. I have added the things you asked me to do and now I am getting the count on the top of the page. The problem is that though it shows me the count of the lines from the LAV report on top but when I try to filter the records in the report that count first of all dosent change and remain the same as the initial number of record though after filtering records reduce and over that the count lines keep on increasing I mean the count is shown in repeated lines afet lines. Kindly help please.
    Thanks
    *& Report  ZSD_BILLING_HDR_TEXT_sum                                       *
    *&         billing doc. and associated header text report              *
    *&                            CHANGE LOG                               *
    *& jpoon 2007.08.03                  Change request: DEVK905095        *
    *& Move request: SD_1451_01          Requestor: Mona Fox               *
    *& FP14134 - original code.                                            *
    REPORT  zsd_billing_hdr_text_sum MESSAGE-ID zsd NO STANDARD PAGE HEADING.
    * For ALV usage
    TYPE-POOLS: slis.
    DATA: gs_layout   TYPE slis_layout_alv,
          tp_print    TYPE slis_print_alv,
          gt_sort     TYPE slis_t_sortinfo_alv,
          gt_events   TYPE slis_t_event,
          t_fieldcat  TYPE slis_t_fieldcat_alv WITH HEADER LINE,
          repid       TYPE syrepid,               " ABAP Program.
          gt_list_top_of_page TYPE slis_t_listheader,     " Top of page text.
          alv_variant   TYPE disvariant," Customize Disp. Variant
          w_event type slis_alv_event.
    DATA: w_field    TYPE slis_fieldcat_alv.
    TABLES: vbrk, vbrp, vbpa.
    DATA  SLIS_EV_AFTER_OUTPUT.
    data: gs_list_top_of_page type slis_listheader.
    *data: gt_list_top_of_page type slis_t_listheader.
    * Definition of selection screen                                       *
    *   By plant, storage location, sold-to customers, material and        *
    *   posting date of the sales orders                                   *
    SELECTION-SCREEN BEGIN OF BLOCK one WITH FRAME TITLE text-001.
    SELECT-OPTIONS: s_vbeln  FOR  vbrk-vbeln,      " billing doc.
                    s_kunnr  FOR  vbpa-kunnr,      " bill-to customer number.
                    s_werks  FOR  vbrp-werks,      " line item plant.
                    s_fkdat  FOR  vbrk-fkdat,      " billing date.
                    s_fkart  FOR  vbrk-fkart,      " billing type.
                    s_vkorg  FOR  vbrk-vkorg.      " sales org.
    PARAMETERS:     p_hold   AS CHECKBOX.
    SELECTION-SCREEN END OF BLOCK one.
    * ALV display layout
    SELECTION-SCREEN BEGIN OF BLOCK layout WITH FRAME TITLE text-003.
    PARAMETERS: pa_vari TYPE slis_vari DEFAULT ' '. " Display variant.
    SELECTION-SCREEN END OF BLOCK layout.
    * Data Definitions                                                     *
    * Storing Extracted Info.
    TYPES: BEGIN OF t_extract,
             vbeln        TYPE vbeln_vf,   " Sales order number.
             posnr        TYPE posnr,      " line item
             fkart        TYPE fkart,      " billing type.
             vtext        TYPE BEZEI20,    " billing type description.
             fkdat        TYPE fkdat,      " billing date.
             werks        TYPE werks_d,    " line item plant.
             werks_name1  TYPE name1,      " plant description.
             kunnr        TYPE kunnr,      " bill-to customer.
             kunnr_name1  TYPE name1_gp,   " bill-to description.
             netwr        TYPE netwr,      " net value,invoice total $
             zzflag       TYPE boolean,    " hold indicator
             zzreason     TYPE char30,     " header text2 (reason)
             zzuser       TYPE ernam,      " last changed by
             zz_changed_date TYPE dats,    " last changed date
             zz_changed_time TYPE tims,    " last changed time
            END OF t_extract.
    DATA: it_extract  TYPE TABLE OF t_extract WITH HEADER LINE,
          it_extract2 TYPE TABLE OF t_extract WITH HEADER LINE.
    DATA: it_text TYPE TABLE OF tline WITH HEADER LINE.
    DATA: wa_thead type thead.
    DATA: w_tdname type TDOBNAME.
    DATA: L_COUNT TYPE I.
    * initialization
    INITIALIZATION.
      gs_layout-colwidth_optimize = 'X'.
      tp_print-no_print_listinfos = 'X'.
      tp_print-no_coverpage = 'X'.
      PERFORM set_fieldcat.
      PERFORM alv_eventtab_build USING:
    **    Event name     Form to execute     Event internal table
       'TOP_OF_PAGE'  'TOP_OF_PAGE'       gt_events[].
    * Dropdown list for all created ALV layouts, global or user-specific
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR pa_vari.
      PERFORM alv_variant_f4 CHANGING pa_vari.
    * Main BODY of processing logic
    START-OF-SELECTION.
      IF s_vbeln IS INITIAL
      AND s_kunnr IS INITIAL
      AND s_werks IS INITIAL
      AND s_fkdat IS INITIAL
      AND s_fkart IS INITIAL
      AND s_vkorg IS INITIAL.
         MESSAGE i000 WITH text-037 ' ' ' ' ' '.
      ELSE.
        PERFORM extract_data.
      ENDIF.
    END-OF-SELECTION.
      IF it_extract2[] IS INITIAL.
        MESSAGE i000 WITH text-002 ' ' ' ' ' '.
      ELSE.
    * Build headings for report.
    *    PERFORM build_top_of_page  USING gt_list_top_of_page[].
    * describe table it_extract2 lines l_count.
    *write :/ 'TOTAL NO OF ENTRIES', SY-VLINE, 32 L_COUNT.
          PERFORM call_alv.
    *write :/ 'TOTAL NO OF ENTRIES', SY-VLINE, 32 L_COUNT.
      ENDIF.
    *&      Form  EXTRACT_KEY_DATA
    * Retreive the data for the report.
    FORM extract_data.
      CLEAR: it_extract.  REFRESH: it_extract.
    * read and select billing documents
      IF p_hold IS INITIAL.
        SELECT vbrk~vbeln vbrk~fkart vbrk~fkdat vbrk~netwr
               vbrk~zzflag vbrk~zzreason vbrk~zzuser
               vbrk~zz_changed_date vbrk~zz_changed_time
               vbrp~posnr vbrp~werks
          INTO CORRESPONDING FIELDS OF TABLE it_extract
          FROM vbrk INNER JOIN vbrp ON
               vbrk~vbeln = vbrp~vbeln
         WHERE vbrk~vbeln IN s_vbeln
           AND vbrk~fkart IN s_fkart
           AND vbrk~fkdat IN s_fkdat
           AND vbrk~vkorg IN s_vkorg
           AND vbrk~fksto NE 'X'
           AND vbrp~werks IN s_werks.
      ELSE.
    * read 'held' documents only as per selection
        SELECT vbrk~vbeln vbrk~fkart vbrk~fkdat vbrk~netwr
               vbrk~zzflag vbrk~zzreason vbrk~zzuser
               vbrk~zz_changed_date vbrk~zz_changed_time
               vbrp~posnr vbrp~werks
          INTO CORRESPONDING FIELDS OF TABLE it_extract
          FROM vbrk INNER JOIN vbrp ON
               vbrk~vbeln = vbrp~vbeln
         WHERE vbrk~vbeln IN s_vbeln
           AND vbrk~fkart IN s_fkart
           AND vbrk~fkdat IN s_fkdat
           AND vbrk~vkorg IN s_vkorg
           AND vbrk~fksto NE 'X'
           AND vbrk~zzflag = 'X'
           AND vbrp~werks IN s_werks.
      ENDIF.
      IF sy-subrc <> 0.
        MESSAGE i000 WITH text-002 ' ' ' ' ' '.
      ENDIF.
      CHECK sy-subrc = 0.
    * only need first line item for this report.
      SORT it_extract BY vbeln posnr.
      DELETE ADJACENT DUPLICATES FROM it_extract COMPARING vbeln.
      LOOP AT it_extract.
    * Retrieve and select by sales order bill-to on header level
    * as well as lookup bill-to customer name/description
        SELECT SINGLE kunnr FROM vbpa INTO it_extract-kunnr
         WHERE vbeln = it_extract-vbeln
           AND posnr = '000000'
           AND parvw = 'RE'.
        IF it_extract-kunnr IN s_kunnr.
          it_extract-kunnr_name1 = zcl_kna1=>get_name1( it_extract-kunnr ).
        ELSE.
          DELETE it_extract.
          CONTINUE.
        ENDIF.
    * lookup billing type description
        SELECT SINGLE vtext FROM tvfkt
          INTO it_extract-vtext
         WHERE spras = sy-langu
           AND fkart = it_extract-fkart.
        IF sy-subrc <> 0.
          clear it_extract-vtext.
        ENDIF.
    * lookup plant description
        SELECT SINGLE name1 FROM t001w
          INTO it_extract-werks_name1
         WHERE werks = it_extract-werks.
        IF sy-subrc <> 0.
          clear it_extract-werks_name1.
        ENDIF.
        MOVE-CORRESPONDING it_extract TO it_extract2.
        APPEND it_extract2.
       ENDLOOP.
    describe table it_extract2 lines l_count.
    ENDFORM.                    " EXTRACT_DATA
    *&      Form  SET_FIELDCAT
    * Create the field catalogue.
    FORM set_fieldcat .
    *CLEAR W_EVENT.
    *W_EVENT-FORM = SLIS_EV_AFTER_OUTPUT.
    *W_EVENT-NAME = SLIS_EV_AFTER_LINE_OUTPUT.
    *APPEND W_EVENT TO GT_EVENTS.
      CLEAR w_field.
      CLEAR t_fieldcat.  REFRESH t_fieldcat.
      w_field-col_pos = 1.
      w_field-fieldname = 'ZZFLAG'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Hold Printing'(005).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 2.
      w_field-fieldname = 'ZZREASON'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Reason'(036).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 3 .
      w_field-fieldname = 'VBELN'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Billing Doc'(028).
      w_field-emphasize = 'X'.
      w_field-hotspot   = 'X'.
      APPEND w_field TO t_fieldcat.
      CLEAR w_field.
      w_field-col_pos = 4 .
      w_field-fieldname = 'VTEXT'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Type Description'(030).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 5 .
      w_field-fieldname = 'FKDAT'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Billing Date'(031).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 6 .
      w_field-fieldname = 'WERKS'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Plant'(012).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 7 .
      w_field-fieldname = 'WERKS_NAME1'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Plant Description'(032).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 8.
      w_field-fieldname = 'KUNNR'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Bill-to Customer'(033).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 9 .
      w_field-fieldname = 'KUNNR_NAME1'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Bill-to Description'(034).
      w_field-emphasize = 'X'.
      w_field-hotspot   = 'X'.
      APPEND w_field TO t_fieldcat.
      CLEAR w_field.
      w_field-col_pos = 10 .
      w_field-fieldname = 'NETWR'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Invoice Amount'(035).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 11 .
      w_field-fieldname = 'ZZUSER'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Changed By'.
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 12 .
      w_field-fieldname = 'ZZ_CHANGED_DATE'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Last Changed Date'(006).
      APPEND w_field TO t_fieldcat.
      w_field-col_pos = 13 .
      w_field-fieldname = 'ZZ_CHANGED_TIME'.
      w_field-tabname = 'IT_EXTRACT2'.
      w_field-seltext_l = 'Last Changed Time'(007).
      APPEND w_field TO t_fieldcat.
    *  W_event-NAME = slis_ev_end_of_list.
    *  W_event-FORM = 'END_OF_LIST'.
    *  APPEND W_event  TO GT_EVENTS.
    *  CLEAR W_event .
    *  w_field-col_pos = 14 .
    *  w_field-fieldname = 'COUNT'.
    *  w_field-tabname = 'IT_EXTRACT2'.
    *  w_field-seltext_l = 'COUNT'.
    *  APPEND w_field TO t_fieldcat.
    ENDFORM.                    " SET_FIELDCAT
    *&      Form  CALL_ALV
    * Call the ALV Grid function.
    FORM call_alv .
      SORT it_extract BY vbeln.
    * repid is necessary since the ALV F.M. does not work properly with
    * sy-repid.
      repid = sy-repid.
      alv_variant-variant  = pa_vari.
      alv_variant-report   = sy-repid.
      alv_variant-username = sy-uname.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
        EXPORTING
          i_callback_program      = repid
          i_callback_user_command = 'USER_COMMAND'
          is_layout               = gs_layout
          it_fieldcat             = t_fieldcat[]
          it_sort                 = gt_sort[]
          i_default               = 'X'
          i_save                  = 'A'
          is_variant              = alv_variant
          it_events               = gt_events[]
          is_print                = tp_print
        TABLES
          t_outtab                = it_extract2
        EXCEPTIONS
          program_error           = 1
          OTHERS                  = 2.
    write :/ 'TOTAL NO OF ENTRIES', SY-VLINE, 32 L_COUNT.
      IF sy-subrc NE 0.
        MESSAGE w000 WITH text-004 ' ' ' ' ' '.
      ENDIF.
    ENDFORM.                    " CALL_ALV
    *&      Form  alv_eventtab_build
    *     Pass list of events to be triggered by the ALV function module
    FORM alv_eventtab_build USING  u_name  TYPE slis_alv_event-name
                                   u_form  TYPE slis_alv_event-form
                                   alv_lt_events  TYPE slis_t_event.
      DATA: ls_event TYPE slis_alv_event.   " structure for event handling
      ls_event-name = u_name.
      ls_event-form = u_form.
      APPEND ls_event TO alv_lt_events.
    ENDFORM.                    " alv_eventtab_build
    *       FORM TOP_OF_PAGE                                              *
    FORM top_of_page.
    *gs_list_top_of_page-type = 'H'.
    GS_LIST_TOP_OF_PAGE-INFO = L_COUNT.
    APPEND GS_LIST_TOP_OF_PAGE TO GT_LIST_TOP_OF_PAGE.
      CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'
        EXPORTING
          i_logo             = 'NEWALTA_LOGO'
          it_list_commentary = gt_list_top_of_page.
    ENDFORM.                    " TOP_OF_PAGE
    *&      Form  user_command
    * Process the user command.
    *      -->R_UCOMM      User command
    *      -->RS_SELFIELD  Field selected
    FORM user_command USING r_ucomm     LIKE sy-ucomm
                            rs_selfield TYPE slis_selfield.
      DATA: ltp_vbeln TYPE vbeln.  " Sales document number.
      CASE  r_ucomm.
        WHEN '&IC1'.
          IF ( rs_selfield-fieldname = 'VBELN'
            OR rs_selfield-fieldname = 'BILL_VBELN' )
           AND rs_selfield-value IS NOT INITIAL.        " Display sales document.
            ltp_vbeln = rs_selfield-value.
            zcl_sales_doc=>display( ltp_vbeln ).
          ENDIF.
      ENDCASE.
    ENDFORM.                    "user_command
    *&      Form  alv_v-ariant_f4
    * Get the display variant.
    *      <--CTP_VARI  Variant name
    FORM alv_variant_f4 CHANGING ctp_vari TYPE slis_vari.
      alv_variant-report   = sy-repid.             " Report ID
      alv_variant-username = sy-uname.             " User ID
      CALL FUNCTION 'REUSE_ALV_VARIANT_F4'
        EXPORTING
          is_variant = alv_variant
          i_save     = 'A'
        IMPORTING
          es_variant = alv_variant
        EXCEPTIONS
          OTHERS     = 1.
      IF sy-subrc = 0.
        ctp_vari = alv_variant-variant.
      ENDIF.
    ENDFORM.                    " alv_variant_f4

  • Count MySQL rows based off Value in Dynamic Table

    Greetings all. I have 2 MySQL tables; 1 that contains the names of my classes.(Class A, Class, B, etc.) and 1 table that contains the names of students in each Class (for example Class A: John Doe; Class A: Susie Smith.; Class B: Jane Doe). In the 2nd table the Class name is in its own column and the student's name is in a 2nd column.
    I currently have a dynamic repeating table that lists the names of all of the classes from the 1st table. What I'm trying to do is add a second column to this repeating dynamic table that lists the number of students in each class. For example; Row 1 of the dynamic table would say "Class A | 5; Class B | 3; Class C | 7, etc.). The dynamic table works perfectly to list the class names. For the life of me I can't figure out how to perform a count for each class to insert in the repeating table. I will be adding more Classes which as why I'm trying to set up the counting query dynamically. So far I have only been able to figure out how to count the total rows in the 2nd table, or count the rows with a specified class name. Any advice or guidance on how to count the number of rows in the 2nd MySQL table based off the class name in the repeating table is much appreciated. Thank you for any and all help. Have a great day.

    Select count(*), Class from MyTable
    Group by Class
    Time to learn about SQL:
    http://www.w3schools.com/sql/sql_intro.asp

Maybe you are looking for