Sql for CrossTab Query

I have the following data on a student table
Regno        Term1          MnMark      Status
xxxx            1                  30            Red
xxxx            2                   50         Amber
xxxx            3                 40           Amber
xxxx           4                 90            Green
I wanto get the report like
Regno              Red           Amber               Green
xxxx                1                    2                    1
Like that. Please give help with proper query
With Thanks
Pol
polachan

create table students (Regno varchar(50), Term1 int, MnMark int, Status varchar(50))
Insert into students values('xxxx',1,30,'Red'),('xxxx',2,50,'Amber'),('xxxx',3,40,'Amber'),('xxxx',4,90,'Green')
declare @cols varchar(200)
declare @sql varchar(2000)
Select @Cols = COALESCE(@Cols + ', ', '') + QUOTENAME(Status) FROM (select distinct Status from students) t
Select @sql='Select Regno, ' + @Cols+' FROM (Select Regno, MnMark, Status from students) src pivot (Count(MnMark) For Status IN (' + @Cols + ' )) pvt'
--Print @sql;
exec (@sql)
--Select Regno,[Red],[Amber], [Green] FROM (Select Regno, MnMark, Status from students) src pivot (Count(MnMark) For Status in ([Red],[Green],[Amber])) pvt
drop table students

Similar Messages

  • Bad SQL for JDO query

    Kodo JDO EE 2.3 RC1 (with InstantDB on JBoss 3.0 on JDK 1.3.1 on Mac
    OS X 10.1.5) generates wrong SQL for a JDO query with a parameter.
    Essentially (unimportant details omitted) I have the following:
    2 associated persistence-capable classes
    public class Person
         private String name;
    public class Issue
         private int id;
         private Person owner;
    both with application-managed identity (Person by name, Issue by id),
    both in the same package. I want to search the database for all Issues
    owned by a certain Person. My code looks like this:
    @pre p is persistent
    Collection findByOwner(Person p){
         // pm is the PersistenceManager
         //TODO pm.newQuery(Issue.class, filter) does not work with Kodo 2.3 RC1
         Extent extent = pm.getExtent(Issue.class, true);
         Query query = pm.newQuery(extent, "owner==person");
         query.setClass(Issue.class);
         query.setIgnoreCache(true);
         query.declareParameters(Person.class.getName() + " person");
         return (Collection)query.execute(p);
    and produces the following SQL statement
    SELECT t0.IDX, t0.JDOCLASSX, t0.JDOLOCKX, t0.NAME_OWNERX FROM ISSUEX
    t0, PERSONX t1 WHERE (t1.NAMEX = NULL AND t0.NAME_OWNERX = t1.NAMEX)
    which is wrong because the actual p.name, which is definitely not nil,
    got lost, and is even rejected by the database*, probably because
    NAMEX is the primary key and cannot be NULL.
    I am pretty sure that this used to work correctly with Kodo 2.2.4. Can
    anyone tell me what I could be doing wrong? I will provide the full
    source code at request.
    Thanks,
    Jakob
    * SQLException:
    Don't understand SQL after: "WHERE"
    Expected: "{" found: "NULL"

    This issue has been resolved in internal builds.
    Some tangential notes about the code below:
    - in our latest version, we no longer require extents when executing
    queries (the candidate class is sufficient).
    - I'm a little concerned about where the 'pm' variable came from in
    Issue.findByOwner(). If that's a member variable, you'd be better off
    doing 'JDOHelper.getPersistenceManager (this)' instead of caching it on
    your own -- this way, you'll avoid any potential issues with somehow
    using the wrong PM or something.
    - Given that all the info is stored in the database already, I'd suggest
    making the relation a bidirectional one, so that you can just traverse
    from Issue to Person without needing to do a query. This will be faster,
    as we will be able to leverage our PM and PMF caches rather than needing
    to execute a query against the data store.
    -Patrick
    Jakob Spies <[email protected]> wrote:
    Kodo JDO EE 2.3 RC1 (with InstantDB on JBoss 3.0 on JDK 1.3.1 on Mac
    OS X 10.1.5) generates wrong SQL for a JDO query with a parameter.
    Essentially (unimportant details omitted) I have the following:
    2 associated persistence-capable classes
    public class Person
    private String name;
    public class Issue
    private int id;
    private Person owner;
    both with application-managed identity (Person by name, Issue by id),
    both in the same package. I want to search the database for all Issues
    owned by a certain Person. My code looks like this:
    @pre p is persistent
    Collection findByOwner(Person p){
    // pm is the PersistenceManager
    //TODO pm.newQuery(Issue.class, filter) does not work with Kodo 2.3 RC1
    Extent extent = pm.getExtent(Issue.class, true);
    Query query = pm.newQuery(extent, "owner==person");
    query.setClass(Issue.class);
    query.setIgnoreCache(true);
    query.declareParameters(Person.class.getName() + " person");
    return (Collection)query.execute(p);
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • What is a efficient SQL for this query ?

    Hi,
    I am using 9.2 database. Suppose I am having following 2 tables
    Table p having only one column i.e. 'a'. Values in this column are
    a1
    b1
    c1
    d1
    Table Q having three columns a, b, c
    a1, 1, 100
    a1, 2, 50
    b1, 1, 30
    b1, 2, 40
    d1, 2, 90
    Table Q can be joined only using column a.
    Table Q can have multiple or no records for column a in table p. Based on above sample data, I want following output
    a1, 100, 50
    b1, 30, 40
    c1
    d1, 90
    Kindly tell be how can I achive this in most efiicient way !!!
    thanks & regards
    PJP

    I only have you two tracks about how do it.
    If you want all the columns from p with or wihout q you have to do:
    11:35:58 SQL> l
    1 select p.*, q.*
    2 from p,q
    3* where p.a = q.a (+)
    11:37:27 SQL> /
    For change the order of the colums for rows you can see the url, the are more examples like that only need to search "columns for rows" in this forums.
    Anyway:
    with rt as
    select 'a1' a, 1 b, 100 c from dual union
    select 'a1', 2, 50 from dual union
    select 'b1', 1, 30 from dual union
    select 'b1', 2, 40 from dual union
    select 'd1', 2, 90 from dual)
    --select * from rt
    select a, decode('1','0','0',rtrim(xmlagg(xmlelement(b, b || ',')).extract('//text()'),',')) b
    , decode('1','0','0',rtrim(xmlagg(xmlelement(c, c || ',')).extract('//text()'),','))
    from rt
    group by a
    Message was edited by:
    cth
    Other way:
    select a, ltrim(b,',') as b, ltrim(c,',') as c
    from (
    select row_number() over (partition by a order by length(b) desc) as rn, a, b,c
    from (select a, sys_connect_by_path(b, ',') as b,
              sys_connect_by_path(c, ',') as c
    from (
    select row_number() over (partition by a order by b) as rn, a, b,c
    from rt) y
    connect by rn = prior rn + 1 and prior a = a
    start with rn = 1
    where rn = 1
    Message was edited by:
    cth

  • How to write SQL for this query

    Hi, All
    I have table which sample data are shown below
    CLM_NO. CLM_RUN PARTY PAY_CD
    2006213103246      2006085483      PA010193 3CO11
    2006213103246      2006085483 PA010193 3CO17
    2006213103246      0000000000 PA084113 2CO11
    2006213103246      0000000000 PA000001 2RK11
    2006213103246      0000000000 PA082822 3CO11
    2006213103270      0000000000 PA000001 2RK11
    2006213103270      0000000000 PA032456 3CO11
    for each clm_no , if data only have zero the report must show pay_cd minimum value(2RK11) but when clm_run have both zero and nonzero data the report will show minimum pay_cd of record that have clm_run nonzero data(3CO11)
    Thank you
    Mcka

    Hi Mcka
    Based on the example you have provided, we should have only the following two rows in the final result:
    CLM_NO. CLM_RUN PARTY PAY_CD
    2006213103246 2006085483 PA010193 3CO11
    2006213103270 0000000000 PA000001 2RK11
    The first line is displayed because even though there are 6 rows for CLM_NO 2006213103246, with a combination of zero and non-zero CLM_RUNS, we need to display the non-zero row containing the minimum PAY_CD.
    The second line is displayed because both rows have a zero CLM_RUN and we need to display the row which has the lowest PAY_CD.
    If this understanding sounds right to you then you need to create the following condition:
    RANK() OVER(PARTITION BY CLM_NO ORDER BY CLM_RUN DESC, PAY_CD ASC) = 1
    Can you follow what this is doing?
    Basically, for each CLM_NO, identified by the clause PARTITION BY CLM_NO, we are ranking the combination of CLM_RUN and PAY_CD where the CLM_RUN is sorted in high to low order and the PAY_CD is sorted in low to high order. This will cause Discoverer to allocate an ascending range of numbers starting with 1, where 1 corresponds to the row you are looking for. If we create a condition such that this whole expression equals 1 then we must display only the rows that you want, with one row being displayed per CLM_NO.
    Note: This works so long as the same CLM_NO cannot have two or more different CLM_RUN numbers where one of the higher CLM_RUNs has a lower PAY_CD than the other non-zero CLM_RUNs.
    It also makes the assumption that for a given non-zero CLM_RUN there will not be two or more identical PAY_CDs. If this condition can exist then you could exclude duplicate values from the report. If you have never done this there is a checkbox called Hide Duplicate Rows on the Layout tab of the Edit Worksheet Dialog box.
    Best wishes
    Michael

  • ORA-01489 Received Generating SQL for Report Region

    I am new to Apex and I am running into an issue with an report region I am puzzled by. Just a foreword, I'm sure this hack solution will get a good share of facepalms and chuckles from those with far more experience. I welcome suggestions and criticism that are helpful and edifying!
    I am on Apex 4.0.2.00.07 running on 10g, I believe R2.
    A little background, my customer has asked an Excel spreadsheet be converted into a database application. As part of the transition they would like an export from the database that is in the same format as the current spreadsheet. Because the column count in this export is dynmic based on the number of records in a specific table, I decided to create a temporary table for the export. The column names in this temp table are based on a "name" column from the same data table so I end up with columns named 'REC_NAME A', 'REC_NAME B', etc. (e.g. Alpha Record, Papa Record, Echo Record, X-Ray Record). The column count is currently ~350 for the spreadsheet version.
    Because the column count is so large and the column names are dynamic I've run into a host of challenges and errors creating this export. I am a contractor in a corporate environmentm, so making changes to the apex environment or installation is beyond my influence and really beyond what could be justified by this single requirement for this project. I have tried procedures and apex plug-ins for generating the file however the UTL_FILE package is not available to me. I am currently generating the SQL for the query in a function and returning it to the report region in a single column (the user will be doing a text-to-column conversion later). The data is successfully being generated, however, the sql for the headers is where I am stumped.
    At first I thought it was because I returned both queries as one and they were joined with a 'union all'. However, after looking closer, the SQL being returned for the headers is about +10K+ characters long. The SQL being returned for the data is about +14k+. As mentioned above, the data is being generated and exported, however when I generate the SQL for the headers I am receiving a report error with "ORA-01489: result of string concatenation is too long" in the file. I am puzzled why a shorter string is generating this message. I took the function from both pages and ran them in a SQL command prompt and both return their string values without errors.
    I'm hopeful that it's something obvious and noobish that I'm overlooking.
    here is the code:
    data SQL function:
    declare
      l_tbl varchar2(20);
      l_ret varchar2(32767);
      l_c number := 0;
      l_dlim varchar2(3) := '''|''';
    begin
      l_tbl := 'EXPORT_STEP';
      l_ret := 'select ';
      for rec in (select column_name from user_tab_columns where table_name = l_tbl order by column_id)
      loop
        if l_c = 1 then
            l_ret := l_ret || '||' || l_dlim || '|| to_char("'||rec.column_name||'")';
        else
            l_c := 1;
            l_ret := l_ret || ' to_char("' || rec.column_name || '")';
        end if;
      end loop;
        l_ret := l_ret || ' from ' || l_tbl;
      dbms_output.put_line(l_ret);
    end;header sql function:
    declare
      l_tbl varchar2(20);
      l_ret varchar2(32767);
      l_c number := 0;
      l_dlim varchar2(3) := '''|''';
    begin
      l_tbl := 'EXPORT_STEP';
      for rec in (select column_name from user_tab_columns where table_name = l_tbl order by column_id)
      loop
        if l_c = 1 then
            l_ret := l_ret || '||' || l_dlim || '||'''||rec.column_name||'''';
        else
            l_c := 1;
            l_ret := l_ret || '''' || rec.column_name || '''';
        end if;
      end loop;
        l_ret := l_ret || ' from dual';
      dbms_output.put_line(l_ret);
    end;-------
    EDIT: just a comment on the complexity of this export, each record in the back-end table adds 12 columns to my export table. Those 12 columns are coming from 5 different tables and are the product of a set of functions calculating or looking up their values. This is export is really a pivot table based on the records in another table.
    Edited by: nimda xinu on Mar 8, 2013 1:28 PM

    Thank you, Denes, for looking into my issue. I appreciate your time!
    It is unfortunately a business requirement. My customer has required that the data we are migrating to this app from a spreadsheet be exported in the same format, albeit temporarily. I still must meet the requirement. I'm working around the 350 columns by dumping everything into a single column, which is working for the data, however, the headers export is throwing the 01489 error. I did run into the error you posted in your reply. I attempted to work around it with the clob type but eneded up running into my string concatentation error again.
    I'm open to any suggestions at this point given that I have the data. I'm so close because the data is exporting, but because the columns are dynamic, the export does me little good without the headers to go along with it.

  • Crosstab query using pure SQL only

    Hi all,
    Found a lot of threads on crosstab, but none seems to address what I need. I need to perform crosstab query using pure SQL only & the number of columns are dynamic. From a query, I obtained the below table:
    Name Date Amount
    Alex 2005-06-10 1000
    Alex 2005-06-20 1000
    Alex 2005-07-10 1000
    Alex 2005-07-20 1000
    Alex 2005-08-10 1000
    Alex 2005-08-20 1000
    John 2005-06-10 2000
    John 2005-06-20 2000
    John 2005-07-10 2000
    John 2005-07-20 2000
    John 2005-08-10 2000
    John 2005-08-20 2000
    And I need to transform it into:
    Name 06-2005 07-2005 08-2005
    Alex 2000 2000 2000
    John 4000 4000 4000
    Reason for the columns being dynamic is because they'll be a limit on the date ranges to select the data from. I'd have a lower & upper bound date say June-2005 to August-2005, which explains how I got the data from the above table.
    Please advise.
    Thanks!

    Hi,
    I couldn't resist the intellectual challenge of a pure SQL solution for a pivot table with a dynamic number of columns. As Laurent pointed out, a SQL query can only have a fixed number of columns. You can fake a dynamic number of columns, though, by selecting a single column containing data at fixed positions.
    <br>
    <br>
    If it were me, I'd use a PL/SQL solution, but if you must have a pure SQL solution, here is an admittedly gruesome one. It shows the sum of all EMP salaries per department over a date range defined by start and end date parameters (which I've hardcoded for simplicity). Perhaps some of the techniques demonstrated may help you in your situation.
    <br>
    <br>
    set echo off
    set heading on
    set linesize 100
    <br>
    select version from v$instance ;
    <br>
    set heading off
    <br>
    column sort_order noprint
    column sal_sums format a80
    <br>
    select -- header row
      1        as sort_order,
      'DEPTNO' as DEPTNO ,
      sys_connect_by_path
        ( rpad
            ( to_char(month_column),
              10
          ' | '
        ) as sal_sums
    from
        select
          add_months( first_month, level - 1 ) as month_column
        from
          ( select
              date '1981-01-01' as first_month,
              date '1981-03-01' as last_month,
              months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
            from dual
        connect by level < total_months + 1
      ) months
    where
      connect_by_isleaf = 1
    connect by
      month_column = add_months( prior month_column, 1 )
    start with
      month_column = date '1981-01-01'
    union all
    select -- data rows
      2 as sort_order,
      deptno,
      sys_connect_by_path( sum_sal, ' | ' ) sal_sums
    from
      select
        dept_months.deptno,
        dept_months.month_column,
        rpad( to_char( nvl( sum( emp.sal ), 0 ) ), 10 ) sum_sal
      from
          select
            dept.deptno,
            reporting_months.month_column
          from
            dept,
            ( select
                add_months( first_month, level - 1 ) as month_column
              from
                ( select
                    date '1981-01-01' as first_month,
                    date '1981-03-01' as last_month,
                    months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
                  from
                    dual
              connect by level < total_months + 1
            ) reporting_months
        ) dept_months,
        emp
      where
        dept_months.deptno = emp.deptno (+) and
        dept_months.month_column = trunc( emp.hiredate (+), 'MONTH' )
      group by
        dept_months.deptno,
        dept_months.month_column
    ) dept_months_sal
    where
      month_column = date '1981-03-01'
    connect by
      deptno = prior deptno and
      month_column = add_months( prior month_column, 1 )
    start with
      month_column = date '1981-01-01'
    order by
      1, 2
    <br>
    VERSION
    10.1.0.3.0
    <br>
    DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01
    10          | 0          | 0          | 0
    20          | 0          | 0          | 0
    30          | 0          | 2850       | 0
    40          | 0          | 0          | 0
    <br>
    Now, if we substitute '1981-03-01' with '1981-06-01', we see 7 columns instead of 4
    <br>
    DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01   | 81-04-01   | 81-05-01   | 81-06-01
    10          | 0          | 0          | 0          | 0          | 0          | 2450
    20          | 0          | 0          | 0          | 2975       | 0          | 0
    30          | 0          | 2850       | 0          | 0          | 2850       | 0
    40          | 0          | 0          | 0          | 0          | 0          | 0
    <br>To understand the solution, start by running the innermost subquery by itself and then work your way outward.

  • Error in SQL Query The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query

    hi Experts,
    while running SQL Query i am getting an error as
    The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    T2.LineText
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,T2.LineText
    how to resolve the issue

    Dear Meghanath,
    Please use the following query, Hope your purpose will serve.
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    CAST(T2.LineText as nvarchar (MAX))[LineText]
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry --where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,CAST(T2.LineText as nvarchar (MAX))
    Regards,
    Amit

  • Can I use a OID rule for a Query SQL Lov of BIP?

    Hi. Can I use OID data (rules) for a query sql lov in BIP? Ex. filters users/store.
    Thank you.
    R.

    Hi,
    I didn't look at the example, but if you want to secure your application then you should use container managed security. Read this .
    Anyway, you could add this before return "good"; in your login_action()
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", user);Then, you can access this from anywhere in the application by using #{sessionScope.username}.
    Pedja

  • Format Column Header in Crosstab Query in Crystal Reports for Enterprise

    Hi
    I am using Crystal reports for Enterprise and I would like to format the Column header of a crosstab query one block of colour say light blue.  However I cannot select the header in isolation to the rest of the cross tab.  All I can select is either column text boxes, which doesnu2019t look good formatted as a different colour to the background of the crosstab.  Or I can only select either entire column or the entire row, which kind of defeats the object of formatting just the column header itself.  Is there a way to isolate the column headers so I can format just the header, as the report is looking extremely bland all in white?
    Many Thanks in advance
    Regards
    Neil

    Alright, here's what you need to do:
    1) RIght-click one of the Column Headers and select 'Format Result Object Element' > Appearance > click on the formula button (fx) beside 'Fill' and use this code:
    if currentrowindex < 0 then crBlue
    You wanted light blue right? So, the rgb value for light blue or sky blue would be 135-206-250. So, you can change the color by modifying the formula like this:
    if currentrowindex < 0 then color(135,206,250)
    If this is not the exact blue you're after, just google!
    Hope this helps!
    -Abhilash

  • RPD - Cannot obtain number of columns for the query result :Working with MS SQL 2012 schema

    Hi All,
    I have created my warehouse in MS SQL 2012.
    For management purpose, I have created different schemas in SQL database
    In RPD, Physical layer, when i view data > I get error as
    [nQSError:16002] Cannot obtain number of columns for the query result.
    [nQSError:16001] ODBC error state : S0002 code : 208 message: [Microsoft][ODBC SQL Server Driver][SQL Server] Invalid object name 'tbl'..
    [nQSError:16001] ODBC error state : S0002 code : 208 message: [Microsoft][ODBC SQL Server Driver][SQL Server] Statements could not be prepared..
    I have already browsed : OBIEE 11g Strange ODBC Driver Error with SQL Server : Total Business Intelligence ... did not help me
    please help!!!

    Hi All,
    After all R&D it is been found that Oracle business administrator( RPD) needs default dbo schema. It doesn't accept custom schema for pulling data.
    If anybody have other views please share.!!
    Thank you

  • Use for a Crosstab Query?

    I have a table with the following metric data in it.
    one entry for a metric, whether its integrity was checked and the date checked.
    I need a report that puts all monthly activity on a single line.
    Examples:
    Here's what the table looks like
    proj_name metric integrity_checked Date
    abc broke Y 01-Apr-08
    abc fixed Y 01-Apr-08
    abc trashed Y 01-Apr-08     
    abc broke Y 01-Mar-08
    abc fixed Y 01-Mar-08
    abc trashed Y 01-Mar-08
    xyz broke Y 01-Apr-08
    yxz fixed Y 01-Apr-08
    yxz trashed Y 01-Apr-08     
    yxz broke Y 01-Mar-08
    yxz fixed Y 01-Mar-08
    yxz trashed Y 01-Mar-08
    Report needs to look like this.
    Prog Metric Apr-08 Mar-08
    abc broke Y Y
    abc fixed Y Y
    abc trashed Y Y
    xyx broke Y Y
    xyz fixed Y Y
    xyz trashed Y Y
    Does this call for a crosstab-type query and if so
    how would I code it?
    I've done one crosstab query before but can't get this one to come out right.
    Thanks
    David

    See this link
    http://www.myoracleguide.com/s/Pivot_Tables.htm

  • Crosstab Query for Remaining Revenue (Count, If, Date Between )

    Hi all, hope you had a great new year.
    I am wanting to create a crosstab query for my Projects which shows ProjectID in the row headers and Time Periods split into months quarter or year as the Column Headers using the [DateAgreed] from the Session table. 
    I have created crosstabs which show revenue from sessions and count of sessions with different time periods but i am trying to make it so that it counts only completed sessions from before the column date, so that i can then multiply by the [SessionCost].
    Any ideas guys?
    Here's what i have been working with;
    TRANSFORM Sum(([tblSession]![SessionCompleted]*[tblProject]![SessionCost])) AS Revenue
    SELECT tblProject.ProjectID, tblCompany.CompanyName
    FROM (tblSession INNER JOIN tblCompany ON tblSession.CompanyID = tblCompany.CompanyID) INNER JOIN ((tblProject INNER JOIN tblProjectMetrics ON tblProject.ProjectID = tblProjectMetrics.ProjectID) INNER JOIN qryProjectStatus ON tblProject.ProjectID = qryProjectStatus.ProjectID)
    ON (tblProject.ProjectID = tblSession.ProjectID) AND (tblCompany.CompanyID = tblProject.CompanyID)
    GROUP BY tblProject.ProjectID, tblCompany.CompanyName, tblProject.Total
    PIVOT Format([DateAgreed],"yyyy-mm");
    Thanks :)

    Hi Gord0oo,
    You could concatenates the data as a result and show in a cell.
    TRANSFORM Sum([tblProject]![SessionCost])) & ";" & Sum([tblSession]![SessionCompleted]) AS Revenue
    Regards
    Starain
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Crosstab query for a report

    I've created the below crosstab query for a report.
    Select Grouping_Condition,Warehouse,Max(Value) Over (Partition By Grouping_Condition,Warehouse) As Total,
    Sum(Value) Over (Partition By Warehouse) As Total_Containers_Per_Warehouse,
    Sum(Vat1Ue) Over () As Total_Containers,
    (Max(Vat1Ue) Over (Partition By Grouping_Condition,Warehouse))
    /(Sum(Vat1Ue) Over (Partition By Warehouse))*100 As Total_Pct
    From
    Seleect Grouping_Condition,Warehouse,Count(*) As Value
    From
    Set1Ect
    T1.Warehouse,Shipped_Weight As Shipped_Tons,T1.Max_Weight As Maxtonnes,
    Case When (Shipped_Weight)< (T1.Max_Weight*0.001)*0.95 Then 'containers_under_95'
    When (Shipped_Weight*0.001) Between (T1.Max_Weight*0.001)*0.95 And (T1.Max_Weight*0.001) Then 'containers_95_100'
    Et1Se 'containers_above_weight'
    End Grouping_Condition
    From
    Tabt1E1 T1
    ,Tabt1E2 T2
    ,Tabt1E3 C
    Where
    T1.Co11 = T2.Col1
    And T1.Col2=C.Col2
    And More Conditions
    Where Warehouse In ('W1','W2','W3','W4','W5')
    Group By (Grouping_Condition,Warehouse)
    The Above Query Gives Me Output Something Like Below:
    Grouping_Condition Warehouse Total Total_Containers_Per_Warehouse Total_Containers Total_Pct
    Containers_95_100 W1 5 10 60 50
    Containers_Under_95 W1 5 10 60 50
    Containers_95_100 W2 10 20 60 50
    I've Got Report In The Below Format
    W1 W2 W3 W4 W5 Total
    Total_Containers 10 20 60
    Containers_95_100 5 10 15
    Containes_95_100_% 50 50 ????
    I Need To Calculate The Total Percentage In The Above Table With ????
    Any Help Is Much Appreciated..

    It appears as though you already have your groupings and counts per grouping, but require a ratio of each groupings count against all other counts. Is that correct ?
    If so, try the new 11g analytic function, something like this:
    select Grouping_Condition
          ,Warehouse
          ,ratio_to_report(Value) over () as Count_Ratio_over_Report
    ..

  • SQL or Powershell query to get the SCOM management group id for SCOM 2007 R2 & 2012 / 2012 R2

    Hi All,
    Can any one provide me the SQL or Powershell query to get the SCOM management group id for SCOM 2007 R2 & 2012 / 2012 R2
    I had a SQL query which will query the data from data warehouse and give the management group id but i have lost it for all 3 above.
    Gautam.75801

    Hi Gautam,
    Hope it helps:
    http://blog.tyang.org/2013/03/13/data-aggregation-field-became-empty-in-opsmgr-2007-linked-performance-report/
    http://blog.tyang.org/2012/09/05/mp-authoring-targeting-rms-or-ms/
    Natalya
    ### If my post helped you, please take a moment to Vote as Helpful and\or Mark as an Answer

  • SQL Joins for Order Query

    If someone could help me figure out what joins I need to do to handle the following, I would be greatly appreciative.
    Our Oracle Order Order Header has flex fields that are used to track a special address by it's code which is stored in Attribute 13 on OE_ORDER_HEADERS_ALL table. We use a site usage code called ADMIN_BY to set up a site in the customers table so we can place the address we are linking here. So for instance, if the order had AB-XXXXXX in it's attribute 13 field, I want to look for this same code in the customer site usage table and find the address in HZ_LOCATIONS table or null if attribute 13 does not have data. My only problem is taking care of the NULL case for all previous orders that did not contain this information.
    This is my sql query whcih works if we have a valid entry in attribute 13. This is also set up for a specific order number for testing only.
    SELECT DISTINCT
    ONT.OE_ORDER_HEADERS_ALL.ORDER_NUMBER, AR.HZ_LOCATIONS.LOCATION_ID, AR.HZ_PARTY_SITES.LOCATION_ID AS LOC_ID,
    AR.HZ_PARTY_SITES.PARTY_SITE_ID, AR.HZ_PARTY_SITES.PARTY_ID, ONT.OE_ORDER_HEADERS_ALL.SOLD_TO_ORG_ID,
    ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE13, ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE14, AR.HZ_LOCATIONS.ADDRESS1,
    AR.HZ_CUST_ACCT_SITES_ALL.PARTY_SITE_ID AS P_SITE_ID, AR.HZ_CUST_ACCT_SITES_ALL.CUST_ACCT_SITE_ID,
    AR.HZ_CUST_SITE_USES_ALL.CUST_ACCT_SITE_ID AS CUST_ACCT_S_ID, AR.HZ_CUST_SITE_USES_ALL.SITE_USE_CODE
    FROM AR.HZ_PARTY_SITES, AR.HZ_LOCATIONS, ONT.OE_ORDER_HEADERS_ALL, AR.HZ_CUST_ACCT_SITES_ALL, AR.HZ_CUST_SITE_USES_ALL
    WHERE AR.HZ_PARTY_SITES.LOCATION_ID = AR.HZ_LOCATIONS.LOCATION_ID AND
    AR.HZ_PARTY_SITES.PARTY_ID = ONT.OE_ORDER_HEADERS_ALL.SOLD_TO_ORG_ID AND
    AR.HZ_PARTY_SITES.PARTY_SITE_ID = AR.HZ_CUST_ACCT_SITES_ALL.PARTY_SITE_ID AND
    AR.HZ_CUST_ACCT_SITES_ALL.CUST_ACCT_SITE_ID = AR.HZ_CUST_SITE_USES_ALL.CUST_ACCT_SITE_ID AND
    ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE13 = AR.HZ_CUST_SITE_USES_ALL.LOCATION AND
    (ONT.OE_ORDER_HEADERS_ALL.ORDER_NUMBER = TO_NUMBER('5074920')) AND (AR.HZ_CUST_SITE_USES_ALL.SITE_USE_CODE = 'ADMIN_BY')
    I tried this code to no avail.
    SELECT DISTINCT
    ONT.OE_ORDER_HEADERS_ALL.ORDER_NUMBER, AR.HZ_LOCATIONS.LOCATION_ID, AR.HZ_PARTY_SITES.LOCATION_ID AS LOC_ID,
    AR.HZ_PARTY_SITES.PARTY_SITE_ID, AR.HZ_PARTY_SITES.PARTY_ID, ONT.OE_ORDER_HEADERS_ALL.SOLD_TO_ORG_ID,
    ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE13, ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE14, AR.HZ_LOCATIONS.ADDRESS1,
    AR.HZ_CUST_ACCT_SITES_ALL.PARTY_SITE_ID AS P_SITE_ID, AR.HZ_CUST_ACCT_SITES_ALL.CUST_ACCT_SITE_ID,
    AR.HZ_CUST_SITE_USES_ALL.CUST_ACCT_SITE_ID AS CUST_ACCT_S_ID, AR.HZ_CUST_SITE_USES_ALL.SITE_USE_CODE
    FROM AR.HZ_PARTY_SITES, AR.HZ_LOCATIONS, AR.HZ_CUST_ACCT_SITES_ALL, ONT.OE_ORDER_HEADERS_ALL, AR.HZ_CUST_SITE_USES_ALL,
    ONT.OE_ORDER_HEADERS_ALL OE_ORDER_HEADERS_ALL_1
    WHERE AR.HZ_PARTY_SITES.LOCATION_ID = AR.HZ_LOCATIONS.LOCATION_ID AND
    AR.HZ_PARTY_SITES.PARTY_SITE_ID = AR.HZ_CUST_ACCT_SITES_ALL.PARTY_SITE_ID AND
    AR.HZ_PARTY_SITES.PARTY_ID = ONT.OE_ORDER_HEADERS_ALL.SOLD_TO_ORG_ID AND
    AR.HZ_CUST_ACCT_SITES_ALL.CUST_ACCT_SITE_ID = AR.HZ_CUST_SITE_USES_ALL.CUST_ACCT_SITE_ID AND
    AR.HZ_CUST_SITE_USES_ALL.LOCATION (+) = OE_ORDER_HEADERS_ALL_1.ATTRIBUTE13 AND
    (ONT.OE_ORDER_HEADERS_ALL.ORDER_NUMBER = TO_NUMBER('5074920')) AND
    (AR.HZ_CUST_SITE_USES_ALL.SITE_USE_CODE (+) = 'ADMIN_BY')
    Any assistance would be greatly appreciated.

    Thanks for the reply Rob.
    Your input did help me return values for my query but I got 5 returned rows where I'm trying to return a single line. I modified my sql query with your recommendations.
    SELECT DISTINCT
    ONT.OE_ORDER_HEADERS_ALL.ORDER_NUMBER, ONT.OE_ORDER_HEADERS_ALL.SOLD_TO_ORG_ID,
    ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE13, ONT.OE_ORDER_HEADERS_ALL.ATTRIBUTE14, AR.HZ_LOCATIONS.ADDRESS1,
    AR.HZ_CUST_SITE_USES_ALL.SITE_USE_CODE
    FROM AR.HZ_PARTY_SITES, AR.HZ_LOCATIONS, AR.HZ_CUST_ACCT_SITES_ALL, ONT.OE_ORDER_HEADERS_ALL, AR.HZ_CUST_SITE_USES_ALL,
    ONT.OE_ORDER_HEADERS_ALL OE_ORDER_HEADERS_ALL_1
    WHERE AR.HZ_PARTY_SITES.LOCATION_ID = AR.HZ_LOCATIONS.LOCATION_ID (+) AND
    AR.HZ_PARTY_SITES.PARTY_SITE_ID (+) = AR.HZ_CUST_ACCT_SITES_ALL.PARTY_SITE_ID AND
    AR.HZ_PARTY_SITES.PARTY_ID = ONT.OE_ORDER_HEADERS_ALL.SOLD_TO_ORG_ID (+) AND
    AR.HZ_CUST_ACCT_SITES_ALL.CUST_ACCT_SITE_ID (+) = AR.HZ_CUST_SITE_USES_ALL.CUST_ACCT_SITE_ID AND
    AR.HZ_CUST_SITE_USES_ALL.LOCATION (+) = OE_ORDER_HEADERS_ALL_1.ATTRIBUTE13 AND
    (ONT.OE_ORDER_HEADERS_ALL.ORDER_NUMBER (+) = TO_NUMBER('5074417')) AND
    (AR.HZ_CUST_SITE_USES_ALL.SITE_USE_CODE (+) = 'ADMIN_BY')
    Here is the results for 2 different Order Numbers
    For the first order which has a null value in attribute 13, here is the results
    NULL     NULL     NULL     NULL     1042nd AVIATION CO.     ADMIN_BY
    NULL     NULL     NULL     NULL     437 APS OUTBOUND FREIGHT     ADMIN_BY
    NULL     NULL     NULL     NULL     DCMC DETROIT - GRAND RAPIDS     ADMIN_BY
    NULL     NULL     NULL     NULL     FB5621     ADMIN_BY
    NULL     NULL     NULL     NULL     NULL     NULL
    For the next order which does have a value in attribute 13,
    5075315     3069     AB-S2303B     IB-S2303B     437 APS OUTBOUND FREIGHT     ADMIN_BY
    5075315     3069     AB-S2303B     IB-S2303B     DCMC DETROIT - GRAND RAPIDS     ADMIN_BY
    5075315     3069     AB-S2303B     IB-S2303B     FB5621     ADMIN_BY
    NULL     NULL     NULL     NULL     1042nd AVIATION CO.     ADMIN_BY
    NULL     NULL     NULL     NULL     NULL     NULL
    What I need is for them both to return a single line. The second order should have read...
    5075315     3069     DCMC DETROIT - GRAND RAPIDS     ADMIN_BY     AB-S2303B     IB-S2303B
    while the first order didn't even list the Order number.
    Any thoughts?

Maybe you are looking for