Sql query to create a report

I am trying to extract a report for some pois, unfortunately I don't know how to formulate the query properly. Some data samples together with the rules for the report are described below:
with my_tab as (select 1 id, 'ACME' supplier, 1 poi, 'A' attr1, 'B' attr2 from dual union all
select 2 id, 'TOMA' supplier, 2 poi, 'C' attr1, 'D' attr2 from dual union all
select 3 id, 'ACME' supplier, 3 poi, 'A' attr1, 'B' attr2 from dual union all
select 4 id, 'TOMA' supplier, 3 poi, 'C' attr1, 'D' attr2 from dual union all
select 5 id, 'ACME' supplier, 4 poi, null attr1, null attr2 from dual union all
select 6 id, 'TOMA' supplier, 4 poi, 'C' attr1, 'D' attr2 from dual union all
select 7 id, 'ACME' supplier, 5 poi, null attr1, 'B' attr2 from dual union all
select 8 id, 'TOMA' supplier, 5 poi, 'C' attr1, 'D' attr2 from dual union all
select 9 id, 'ACME' supplier, 6 poi, null attr1, null attr2 from dual union all
select 10 id, 'TOMA' supplier, 6 poi, null attr1, 'D' attr2 from dual)
rules for the resultset:
a) each distinct poi has to occur exactly once
b) if there is more than one record having the same poi id, the attributes from supplier ACME are preferred
c) if ACME is not able to provide an attribute, the supplier TOMA has to step in
The result should look like this:
poi | attr1 | att2
1 | A | B |
2 | C | D |
3 | A | B |
4 | C | D |
5 | C | B |
6 | null | D |
Edited by: user8914294 on Dec 21, 2009 11:58 AM
Edited by: user8914294 on Dec 21, 2009 11:59 AM

Hi,
Welcome to the forum!
Here's one way:
SELECT       poi
,       MAX (attr1) KEEP (DENSE_RANK FIRST ORDER BY CASE
                                                                   WHEN  attr1  IS NOT NULL     THEN 1
                                                               END
                              ,           CASE  supplier
                                        WHEN  'ACME'  THEN  1
                                        WHEN  'TOMA'  THEN  2
                                                               END
                  ) AS attr_1
,       MAX (attr2) KEEP (DENSE_RANK FIRST ORDER BY CASE
                                                                   WHEN  attr2  IS NOT NULL     THEN 1
                                                               END
                              ,           CASE  supplier
                                        WHEN  'ACME'  THEN  1
                                        WHEN  'TOMA'  THEN  2
                                                               END
                  ) AS attr_2
FROM       my_tab
GROUP BY  poi
ORDER BY  poi
;This does not rely on the fact that there are only two suppliers, or that the combination (poi, supplier) is unique, or that the order of preference for suppliers is the same as alphabetic order.
This is an example of a Top-N Query , where you want N items (N=1 in this case) from the top of a sorted list. The problem is, how can we sort the values so that the more desirable ones come at the top of the list?
There are two things that make one value more desirable than another:
(1) Non-NULL values are better than NULL. After that:
(2) Rows where supplier='ACME' are more desireable than rows where supplier='TOMA'.
As it happens, both of these require CASE expressions (or siomething similar, like NVL2) to sort.
Thanks for posting the sample data in such a useful format! That helps a lot.

Similar Messages

  • Extracting the Logical sql query for the specified report  in OBIEE 11g

    Hi ,
    I want to extract the logical SQL Query for the Particular report in OBIEE 11.1.1.5.
    Any pointers related to this will be very helpful.
    Thanks,
    Sonali

    for a try please add Logical sql view to ur report it will dispaly the Logical sql for that Report..
    Hope it will helps you.

  • SQL QUERY to create new schema in Oracle 10g Express

    Can anyone provide the SQL query to create a new schema in Oracle 10g Express edition.

    Can anyone provide a SQl query to create a
    schema/user named 'test' with username as 'system'
    and password as 'manager'system user is created during database creation, it's internal Oracle admin user that shouldn't be used as schema holder.
    In Oracle database, Oracle user is schema holder there's no seperate schema name to be defined other than username.

  • I want a smiple sql query  to create a calender

    Hi,
    I can not find my sql query to create a calender.
    It is just the one who already shows when you create a calender.
    I am writing documentation and I have no acces to Oracle Portal anymore.
    Can somebody give me that sql query ?
    Thanks a lot,
    Chu Lam

    Hi,
    This the one.
    select
    EMP.HIREDATE the_date,
    EMP.ENAME the_name,
    null the_name_link,
    null the_date_link,
    null the_target
    from SCOTT.EMP
    order by EMP.HIREDATE
    Thanks,
    Sharmila

  • SQL Query Too Large For Report Region

    Oracle Friends:
    I have a SQL query that is 24,000 characters long. APEX fails when I try to create a report using this query, probably because it is too long.
    I get an "ORA-01461: can bind a LONG value only for insert into a LONG column" after I paste it and try to go to the next page.
    Any ideas? I can't make my query any smaller without creating intermediate tables.
    Any help would be most appreciated.
    Regards,
    Rich Locus

    Hi,
    If possible, try to reduce the no. of characters from your SQL query. Ex. use shorter aliases etc in your query. Also, as suggested above, create some views which can form a part of your query and then use those views in your main query to reduce the total no. of characters.
    The report region source can take some limited no. of characters only. Exact figure is not known to me.
    Try the above suggestion and see if this works or not.
    Regards,
    Mangal

  • SQL Query based BI Pub report - Taking too long to produce the output

    Hi All,
    I was trying to produce a BI Publisher based report through enterprise edition of BI Publisher 10.1.3.4
    Its a sql query based report and it has around 20 columns and it has around 1 lakh records.
    The query actually takes only 2 seconds to execute in the database but when we execute from BI Publisher it takes a long time and also it times out most of the time
    Is there something I am missing in the configuration options ?
    Thanks
    Shasi

    I am facing the same problem as well. I am using the Publisher Web service API to run a report with 1 Million records. This report is configured to use OBIEE. It takes a lot of time to generate the report ( around 30 Mins) and even though OBIEE generates the data, my web service client either timesout. Even after increasing the timeout, a 500 internal server error is thrown . Does anyone know of a solution to this.
    Thanks

  • SQL Query to get statistics report

    Hi Experts,
    I need to get a report for CPU utilization,Memory Usage,Event Waits, Connection Spool and Shared Spool for a given query.
    Need some tips from you to get that report.
    Thanks,

    Its not something to trace my slow running sql query.
    I need to provide a report regarding Database Statistics on a specific process from front end PHP.
    Previously, i have provided you the different environment Oracle Version, here is the exact version in which i need to generate the report.
    BANNER                                                                         
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production   
    PL/SQL Release 11.1.0.7.0 - Production                                         
    CORE     11.1.0.7.0     Production                                                     
    TNS for Solaris: Version 11.1.0.7.0 - Production                               
    NLSRTL Version 11.1.0.7.0 - Production                                          This Database server is controlled by Client and having just limited access (not able to access the Trace Files).
    Can someone tell me to generate the requested report using some v$ Views.
    Thanks,
    Edited by: DharanV on Apr 15, 2010 8:01 PM
    added some more details to make it much clear

  • How to execute SQL Query from the Crystal report X1

    Dear All,
    I am using crystal report X1. In my application am creating run time MS Access tables and giving table name at run time based on my requirement . From these tables I want to fetch data based on some condition and to display using crystal report X1. I have never used the SQL Queries in the Crystal reports. Please help me out.
    Thanks and Regards,
    Rahaneef T

    Please note;
    This forum is dedicated to all other development-related questions which are not directly addressed by other forums. This includes Business Objects SDKs, products, or technologies which do not fall under BusinessObjects Enterprise, BusinessObjects Edge, Crystal Reports Server, or Crystal Reports (for example Desktop Intelligence SDK, Universe Designer SDK, Portal Integration Kits, Java User Function Libraries, and other third party technologies or development languages).
    This looks more like a Crystal Reports design issue?
    Ludek

  • Concatenate results SQL query and CASE use Report Builder Reporting Services

    I need to concatenate the results from a SQL query that is using CASE.  The query is listed below.  I do not need permitsubtype but I need to concatenate the results from the permittype. 
    I tried deleting the permitsubtype query and it would not run correctly.  Please see the query and diagram below.  Any help is appreciated.
    select  PERMIT_NO
    ,(case when
      ISNULL(PERMITTYPE,'') = ''
      then 'Unassigned'
      else (select LTRIM(RTRIM(PERMITTYPE)))
      END) AS PERMITTYPE
    ,(case when
      ISNULL(PERMITSUBTYPE,'') = ''
      then 'Unassigned'
      else (select LTRIM(RTRIM(PERMITSUBTYPE)))
      END) AS PERMITSUBTYPE
     ,ISSUED
     ,APPLIED
     ,STATUS 
     ,SITE_ADDR 
     ,SITE_APN
     ,SITE_SUBDIVISION
     ,OWNER_NAME
     ,CONTRACTOR_NAME
     ,ISNULL(JOBVALUE,0) AS JOBVALUE
     ,FEES_CHARGED
     ,FEES_PAID
    ,BLDG_SF
    from Permit_Main
    where ISSUED between @FromDate and @ToDate

    Hi KittyCat101,
    As per my understanding, you used case when statement in the query, you do not need to display permitsubtype in the report, but when you tried to delete permitsubtype from the query, it could not run correctly. In order to improve the efficiency of troubleshooting,
    I need to ask several questions:
    “I tried deleting the permitsubtype query and it would not run correctly.” As we can see, it has no effect to delete permitsubtype from the query you provided, could you please provide complete sql query for the report?
    Could you please provide detailed information about the report? I would be appreciated it if you could provide sample data and screenshot of the report.
    Please provide some more detailed information of your requirements.
    This may be a lot of information to ask for at one time. However, by collecting this information now, it will help us move more quickly toward a solution.
    Thanks,
    Wendy Fu

  • Executing PL-SQL Query before running a Report

    Hi Guys,
    Can i use a Run a Pl-Sql Query every time before executing a report. Like if i am opening a report then the pl-sql Query should run before it.
    Thanks
    Rondo.

    Try with Evaluate as one of the column's expression.. so that we can limit to specific report..
    or
    Use Connection Pool->Connection Pool Scripts tab->use 'Execute before query'
    Since we can set the repository variables using advanced tab.. the same variable we may validate using Connection pool scripts tab.
    This might be more dev work..
    Edited by: Srini VEERAVALLI on Dec 17, 2012 9:00 PM

  • SQL Query to BI Publisher Report

    I'm new to BI Publisher. My results from my SQL query did not load properly into BI Publisher. Below is the XML. Can someone help? Thanks!
    <?xml version="1.0" ?>
    - <RESULTSET>
    - <ROWSET id="0">
    - <ROW id="1">
    - <COLUMN NAME="ID">
    - <![CDATA[
    12345
      ]]>
    </COLUMN>
    - <COLUMN NAME="NAME">
    - <![CDATA[
    Mary Jones
      ]]>
    </COLUMN>
    <COLUMN NAME="Gender">F</COLUMN>
    <COLUMN NAME="Address">10-10 203rd Street</COLUMN>
    <COLUMN NAME="City">New York</COLUMN>
    <COLUMN NAME="State">NY</COLUMN>
    <COLUMN NAME="Zip">10013</COLUMN>
    - <COLUMN NAME="Notes">
    - <![CDATA[
    Pending application submission.
      ]]>
    </COLUMN>
    <COLUMN NAME="Birth Date">8/1/1975</COLUMN>
    </ROW>
    </ROWSET>
    </RESULTSET>

    Hi Sonal,
    a possible solution for this can be the use of a lead function (take a look once here where the function is explained http://www.oracle-base.com/articles/misc/LagLeadAnalyticFunctions.php)
    Hope this can help you out.
    Kr
    A

  • SQL Query to create a Time Dimension at 15 mins granuality

    I need a query to generate Time Hierarchy for Year, Half Year, Qtr, Month, Week, Days, Hours, 15 minutes interval
    Pls share the query to generate the same or Excel sheet with the data.
    Thanks
    Anky

    Can you clarify your request a bit?
    Check the following blog for datetime sequence generation:
    http://www.sqlusa.com/bestpractices2005/sequence/
    Recursive CTE is used to generate the sequence.
    Hierarchical DimDate in AdventureWorksDW2012:
    CREATE TABLE [dbo].[DimDate](
    [DateKey] [int] NOT NULL,
    [FullDateAlternateKey] [date] NOT NULL,
    [DayNumberOfWeek] [tinyint] NOT NULL,
    [EnglishDayNameOfWeek] [nvarchar](10) NOT NULL,
    [SpanishDayNameOfWeek] [nvarchar](10) NOT NULL,
    [FrenchDayNameOfWeek] [nvarchar](10) NOT NULL,
    [DayNumberOfMonth] [tinyint] NOT NULL,
    [DayNumberOfYear] [smallint] NOT NULL,
    [WeekNumberOfYear] [tinyint] NOT NULL,
    [EnglishMonthName] [nvarchar](10) NOT NULL,
    [SpanishMonthName] [nvarchar](10) NOT NULL,
    [FrenchMonthName] [nvarchar](10) NOT NULL,
    [MonthNumberOfYear] [tinyint] NOT NULL,
    [CalendarQuarter] [tinyint] NOT NULL,
    [CalendarYear] [smallint] NOT NULL,
    [CalendarSemester] [tinyint] NOT NULL,
    [FiscalQuarter] [tinyint] NOT NULL,
    [FiscalYear] [smallint] NOT NULL,
    [FiscalSemester] [tinyint] NOT NULL)
    Kalman Toth Database & OLAP Architect
    Free T-SQL Scripts
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Use the results of an SQL query to create another query

    I am working on a bidding/allocation system using C# and MySQL, and I am currently having difficulty implementing the “post-allocation” mechanics of the system. Let me explain how it works, before introducing the code:
    When the bids are made on the system, they all have the position 0, so the first thing the system does is order them according to priority.
     (bid table)
    In this case, 5 bidders are interested in what is in plot 15, but we have not assigned them a position yet.
     (bid table)
    The system then organises the bids according to the order in which they are going to processed.
    The bids are then allocated, but unfortunately there are only 3 spaces in plot 15 that can be allocated. As a result, we use the priority listing to determine which bidder gets what.
     (booking table)
    At this stage, I can say that I am stuck, there are two things that I want to do, both of which involve reusing the results of the query at step 2.
     (bid table)
    The bidders that have their job allocated should see: their bid.status updated
    from Queued to Allocated,
    the bid.position should
    be set to 0,
    and their job_id should
    be set to the booking they have been allocated (i.e. booking.id).
    The bidders that have not had their jobs allocated should see: their bid.status remain
    as Queued, and their bid.position should
    be set to 0 in
    preparation for the method to run again
    The difficulty I am having is in stage 3, how do I determine which jobs have been allocated and which ones have not, and then run the necessary SQL queries in order to make the updates?
    My code so far is as follows:
    // STEP 1a - SELECT BIDS
    string query =
    "SELECT t1.operator_id, t1.datetime, t1.plot_id, t1.position, t2.market_access FROM bid t1 " +
    "JOIN operator t2 ON t1.operator_id = t2.id WHERE t1.status='Queued' AND t1.postcode=@postcode " +
    "ORDER BY t2.market_access ASC, t1.datetime ASC";
    var bidList = new List<BidList>();
    var cmd = new MySqlCommand(query, _connection);
    cmd.Parameters.AddWithValue(("@postcode"), _plot);
    MySqlDataReader dataReader = cmd.ExecuteReader();
    while (dataReader.Read())
    var item = new BidList
    OperatorId = dataReader["operator_id"] + "",
    PlotId = dataReader["plot_id"] + "",
    Position = dataReader["position"] + "",
    Datetime = dataReader["datetime"] + "",
    MarketAccess = dataReader["market_access"] + "",
    bidList.Add(item);
    dataReader.Close();
    // STEP 1b - SET PRIORITIES
    for (var i = 0; i < bidList.Count; i++)
    var position = i + 1;
    bidList[i].Position = position.ToString();
    query = "UPDATE bid SET position=@position WHERE status='Queued' AND postcode=@postcode AND operator_id=@operator_id;";
    cmd = new MySqlCommand(query, _connection);
    cmd.Parameters.AddWithValue(("@position"), position);
    cmd.Parameters.AddWithValue(("@postcode"), _plot);
    cmd.Parameters.AddWithValue(("@operator_id"), bidList[i].OperatorId);
    cmd.ExecuteNonQuery();
    dataReader.Close();
    // STEP 2 - ALLOCATE JOBS ACCORDING TO PRIORITY
    foreach (var t in bidList)
    query = "SELECT operator_id, plot_id, status FROM booking " +
    "WHERE status='open' AND postcode=@postcode AND operator_id='0'" +
    "ORDER BY datetime ASC;" +
    "UPDATE booking SET operator_id=@operator_id, status='Allocated' " +
    "WHERE (plot_id=@plot_id AND operator_id='0' AND status='Open') LIMIT 1;";
    cmd = new MySqlCommand(query, _connection);
    cmd.Parameters.AddWithValue(("@operator_id"), t.OperatorId);
    cmd.Parameters.AddWithValue(("@postcode"), _plot);
    cmd.Parameters.AddWithValue(("@plot_id"), t.PlotId);
    cmd.ExecuteNonQuery();
    dataReader.Close();
    // STEP 3
    CloseConnection();

    I can't tell.  When modifying row(s) you have to be able to uniquely be able to identify the row(s) in the database you want to modify.  That is why I recommended the other day to use DataAdapter instead of the DataReader.  You can with the
    reader, but you need to unique identify the rows.
    I can't tell from the limited amount of data you posted if in table 2 that there is only one row with the same operator id and plot id.  It looks like in table 2 the 'id' number is unique.  When working with a database with multiple tables you
    need to be able to link tables together with primary keys (columns wit unique values).  If the database isn't designed properly then it is impossible to do some operations.  So you always have to make sure you design a database properly.
    jdweng
    When you say table 2 are you referring to the bid or booking table?
    Here is the table structure for the bid table
    Here is the table structure for the booking table
    Hope it helps makes things clearer!

  • SQL query problem using analytical/report function

    Hello there,
    I am having some problem writing my query. I have this table below:
                  create table t (priority number,
                                  plannedamount number,
                                  availablepieces number,
                                  material_id varchar2(20))
    insert into t values (1, 15, 30, 'A');
    insert into t values (2, 20, 30, 'A');
    insert into t values (3, 5, 30, 'A');
    insert into t values (4, 8, 30, 'A');
    insert into t values (5, 4, 30, 'A');
    insert into t values (1, 2, 10, 'B');     PRIORITY|     PLANNED AMOUNT|AVAILABLE PIECES |     MATERIAL_ID
         1      15     30 A     
         2      20     30 A
         3      5     30 A
         4      8 30 A
         5      4     30 A
         1      2     30 B .
    Each line is a customer order ordering a material. I am grouping by material and ordering it by priority. I want to display a new column called pieces not reserved yet. This column will show that if the order can be fully reserved for that current order ordering by priority.
    If the row can be reserved it will substract and bring it to the next row. If it cannot the pieces not reserved will remain the same.
    I've tried using sum(), lead(), first(), lag(), etc but I still cannot get the correct result.
         PRIORITY|     PLANNED AMOUNT|PIECES NOT RESERVED YET |     MATERIAL_ID
         1      15     30 A     
         2      20     15 A
         3      5     15 A
         4      8     10 A
         5      4     2 A
         1      2     30 B
    Can anyone elaborate or have any hints on what method to use to create this column?
    Thanks. .
    Edited by: 998373 on Apr 5, 2013 11:42 AM
    Edited by: 998373 on Apr 5, 2013 11:43 AM

    From 10.x on
    with t(PRIORITY, PLANNED_AMOUNT,AVAILABLE_PIECES , MATERIAL_ID) as
    select      1, 15, 30, 'A' from dual union all
    select 2, 20, 30, 'A' from dual union all
    select 3, 5, 30, 'A' from dual union all
    select 4, 8, 30, 'A' from dual union all
    select 5, 4, 30, 'A' from dual union all
    select 1, 2, 30, 'B'  from dual
    select
      MATERIAL_ID
    , PRIORITY
    , PLANNED_AMOUNT
    , AVAILABLE_PIECES PIECES_NOT_RESERVED_YET
    from t
    model
    partition by (material_id)
    dimension by (PRIORITY)
    measures (
      PLANNED_AMOUNT
    , AVAILABLE_PIECES
    rules (
    AVAILABLE_PIECES[priority>1] order by priority=
      case when PLANNED_AMOUNT[cv()-1] <= AVAILABLE_PIECES[cv()-1]
           then AVAILABLE_PIECES[cv()-1] - PLANNED_AMOUNT[cv()-1]
           else AVAILABLE_PIECES[cv()-1]
      end
    MATERIAL_ID     PRIORITY     PLANNED_AMOUNT     PIECES_NOT_RESERVED_YET
    A     1     15     30
    A     2     20     15
    A     3     5     15
    A     4     8     10
    A     5     4     2
    B     1     2     30

  • Handling DST in SQL Query for UCCX Custom Report

    We wrote all custom reports for one of the call centers using our UCCX deployment.  One problem we see we will hit in the future is DST.  We suggested they use UTC but they wanted to see the call data based off of EST timezone.  Right now we are okay because we use -5 to get the correct data but come March we are wondering how to address the issue.  What options do we have?  How are other people handling DST with the SQL queries for custom reporting?  I see that the HR client will determine this based off of the local computer time then gives you the option to use UTC.  We have all of our queries in an Excel document that the customer just needs to open and select Refresh All to update their data.
    Thanks

    "case-when" statements are evaluated in order.
    so you must do something like this:
    SELECT
    CASE WHEN <is not number>THEN 'N'
    CASE WHEN <is greater than 0>THEN 'Y'
    Now "<is greater than 0>" will always have number for input, can't get "not number" error there.
    See this thread:
    Re: regular expression: integer is between N..M
    Edited by: CharlesRoos on May 27, 2010 5:03 AM

Maybe you are looking for

  • [SOLVED] Fresh Install - LXDE - Missing Window Decorations

    Hi folks, I just did a fresh install on my netbook (Asus 1000h) which went flawless as allways. I did install Xorg, the relevant intel drivers, some small stuff like screen and the like and then went on to install LXDE as the desktop environment + th

  • Which other languages compliment AS3/flash?

    So, i've been learning some flash and AS3 recently as part of my job and i plan on learning some more. I have another project starting soon (the details of which i've posted at the bottom but aren't necessarilly relevant for this discussion*). Basica

  • 6210 Nav. power save and light

    Hi guys, wonder if someone could assist me is a couple of newbie questions with the 6210 Navigator. 1 - Can I prevent the screen from dimming and going into power save? i.e. Keep the screen on permanently while using the Navigator / Sat Nav function.

  • Compile option is missing in the Packaging wizard

    I need to compile my local app jsp files but the problem is i could not able to find the compile option in the Packaging wizard. Can anyone advice how to compile  ?  The compile option is missing in the packing wizard. I was using it before without a

  • Problema con psd's de capas colocados en illustrator cs3

    Cuando coloco en illustrator cs3 3 ó 4 archivos psd con capas de peso desde 40MB a 200MB llega un momento que o no me deja previsualizar en color o se me cierra el programa inseperadamente. Trabajo en un mac G5 intel de última generación con 8GBde ra