Newbie - help with a SQL query for a bar chart  - Originally posted in APEX

I originally posted this in the APEX forum but someone there suggested this is more of a SQL question.  Anyone out there who can provide some assistance?
Hi,
I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
select null link
, CATEGORY label
, count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
, count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
from GRAPO_PROHEADTRK
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
group by CATEGORY
Order by COUNT(PROJECT_ID) DESC
The code from the other app was:
select null link
, FUNCTIONAL_AREA label
, count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
, count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
, count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
from PM_V2
where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
group by FUNCTIONAL_AREA
Order by COUNT(PROJECT_ID) DESC
I'm getting a "Failed to parse SQL query!" error when I try to run validation.
Is this enough info for some assistance? Any help would really be appreciated.
Thanks,
Rachel

Hi, Rachel,
user10774102 wrote:
I originally posted this in the APEX forum but someone there suggested this is more of a SQL question.  Anyone out there who can provide some assistance?
Hi,
I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
select null link
, CATEGORY label
, count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
, count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
from GRAPO_PROHEADTRK
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
group by CATEGORY
Order by COUNT(PROJECT_ID) DESCIs there a problem with the code above?
It's curious that the WHERE clause includes "PROJECT_STATUS='6'", but there is no pivoted column for project_status='6', like there is for '1' through '5'. That's not necessarily a mistake, and it wouldn't raise an error in any case.
Instead of
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')you could say
where PROJECT_STATUS  IN ('1', '2', '3', '4', '5', '6')but that probably has nothing to do with your current problem.
The code from the other app was:
select null link
, FUNCTIONAL_AREA label
, count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
, count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
, count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
from PM_V2
where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
group by FUNCTIONAL_AREA
Order by COUNT(PROJECT_ID) DESC
I'm getting a "Failed to parse SQL query!" error when I try to run validation.Is that an Apex error message? Sorry, I don't know anything about Apex.
If you can't get a more specific error message from Apex, then try debugging this statement in SQL*Plus. When you get it fixed, then you can copy it back into Apex.
If this is a SQL problem, then you should be able to re-create the problem in pure SQL.
If you can't re-create the problem in pure SQL, then it's probably an Apex problem, and belongs in the Apex forum, not here.
I don't see anything obviously wrong with your code, but I can't tell if, for example, you spelled a column name wrong, or if something has the wrong data type
Is this enough info for some assistance? Any help would really be appreciated.It wiould be better if you posted a completE script that people could run to re-create the problem, and to test their ideas.
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
Always say which version of Oracle (and any other software, such as Apex) you're using.

Similar Messages

  • Newbie - need help with a SQL query for a bar chart

    Hi,
    I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORY
    Order by COUNT(PROJECT_ID) DESC
    The code from the other app was:
    select null link
    , FUNCTIONAL_AREA label
    , count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
    , count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
    , count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
    from PM_V2
    where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
    group by FUNCTIONAL_AREA
    Order by COUNT(PROJECT_ID) DESC
    I'm getting a "Failed to parse SQL query!" error when I try to run validation.
    Is this enough info for some assistance? Any help would really be appreciated.
    Thanks,
    Rachel

    Hello,
    This is more of an SQL question, rather than specifically APEX-related. It's notable that you say: I'm a new user on APEX with no real SQL knowledgeWhich is fine (we all have to start somewhere, afterall) but it might be worth de-coupling the problem from APEX in the first instance. I'd also strongly recommend either taking a course, reading a book (e.g. http://books.google.co.uk/books?id=r5vbGgz7TFsC&printsec=frontcover&dq=Mastering+Oracle+SQL&hl=en#v=onepage&q=Mastering%20Oracle%20SQL&f=false) or looking for a basic SQL tutorial - it will save you a whole lot of heartache, I promise you. Search the oracle forums for the terms "Basic SQL Tutorial" and you should come up with a bunch of results.
    Given that you've copied your query template from another, I would suggest ensuring that the actual query works first of all. Try running it in either:
    * SQL Editor
    * SQL*Plus
    * an IDE like SQL Developer (available free from the OTN: http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html ) or TOAD or similar.
    You may find there are syntax errors associated with the query - it's difficult to tell without looking at your data model.
    select null link
    , CATEGORY label
    , count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
    , count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
    , count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
    , count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
    , count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
    from GRAPO_PROHEADTRK
    where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
    group by CATEGORYNote that your "order by" clause references a field called "PROJECT_ID", which exists in the old query but you've changed other similar references to "PROJECT_STATUS" - is it possible you've just missed this one? The perils of copy-paste coding I'm afraid...

  • Help with an SQL Query on the Logger

    We are running UCCE 8.5(3) and need help with an SQL query. When I run the below I would also like to see skill group information(name preferably)? Any help would be greatly appreciated!
    select * from dbo.t_Termination_Call_Detail where DateTime between '10-11-2012 00:00:00:00' and
    '10-11-2012 23:59:59:59'

    David, thanks for replying.  Unfortunitly I don't know enough about SQL to put that into a query and have it return data.  Would you be able to give an example on what the query would look like?

  • Help with T-SQL query

    I have 3 hierarchical tables. [Parent] ->[Child1]->[Child2]
    I have [Xref] table which stores the documents associated with these three tables. In the [Xref] table, the column “TypeID” defines to which table the document is associated with.
    Below is the table structure with some sample data.
    Question: Given parented I want to get all the documents associated with parent as well its children. My sql query uses Union and its working fine. But Is there any other simple way to re-write this query?
    (Note that this is just an example, the actual hierarchy is pretty long so my SQL is getting little messy and I want simplify it.)
    TYPES
    TypeID TypeName
    1 Parent
    2 Child1
    3 Child2
    TABLE - PARENT
    ParentID
    1
    2
    3
    TABLE - CHILD1
    Child1ID ParentID
    1 1
    2 1
    3 2
    TABLE - CHILD2
    Child2ID Child1ID
    1 1
    2 1
    3 2
    4 2
    XREF
    DocumentID TypeID LocatorID
    1 1 1
    2 1 2
    3 1 3
    4 2 1
    5 2 2
    6 2 3
    7 3 1
    8 3 2
    9 3 3
    10 3 4
    SELECT DocumentID FROM XREF X
    JOIN Parent P ON P.ParentID = x.LocatorID AND TypeID = 1 -- Parent
    WHERE P.ParentID = @ParentID
    UNION
    SELECT DocumentID FROM XREF X
    JOIN Child1 C1 ON C1.Child1ID = x.LocatorID AND TypeID = 2 -- Child1
    JOIN Parent P ON P.ParnetID = C1.ParentID
    WHERE P.ParentID = @ParentID
    UNION
    SELECT DocumentID FROM XREF X
    JOIN Child2 C2 ON C2.Child1ID = x.LocatorID AND TypeID = 3 -- Child2
    JOIN Child1 C1 ON C1.Child1ID = c2.Child1ID
    JOIN Parent P ON P.ParnetID = C1.ParentID
    WHERE P.ParentID = @ParentID

    Can you child span multiple levels? If yes, best way would be to use CTE
    see
    http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Selection screen - search help with dynamic sql query

    hey ,
    is it possible to change the search help of the selection field ?
    when i create the range table i put a data element :
    create a range table that consists of this new data element
      LT_RANGE_TABLE = WD_THIS->M_HANDLER->CREATE_RANGE_TABLE( I_TYPENAME = 'S_CARR_ID' ).
    can i control the search help via the the data element or by other methods ?
    i want that when the user press F4 the values that will show is the result of a sql query that i will write .
    is it possible ?
    thanks
    ASA.

    Hi,
    yes it is possible...
    This is my test code for say personal number select options...
    lt_range_table = wd_this->m_handler->create_range_table(
      i_typename = 'PERSNO' ).
    add a new field to the selection
      wd_this->m_handler->add_selection_field(
      i_id = 'PERSNO'
    I_VALUE_HELP_TYPE = if_wd_value_help_handler=>CO_PREFIX_SEARCHHELP
    I_VALUE_HELP_ID = 'ZHELP_WDA_PERNR'   "this is the custom search help we need to create
    I_NO_INTERVALS = abap_true
      it_result = lt_range_table
      i_read_only = read_only ).
    do the following:
    1) copy the std function module: F4IF_SHLP_EXIT....to ZF4IF_SHLP_EXIT_pernr (in my case i am testing for pernr so my fm
    name is like that....obviously it can be anything you want...under the recommended naming convention)
    2) look for "STEP SELECT"
    STEP SELECT    (Select values)
    3)write the code as follows:
    "NOTE: this is my testing code...but you can build your logic on it....
    IF CALLCONTROL-STEP = 'SELECT'.
    types: begin of zpri_listing,
    pernr type PERSNO,
    end of zfund_listing.
    DATA: lo_syuname TYPE sy-uname.
    data itab type standard table of Zpri_LISTING.
    data wa type zpri_listing.
        DATA : t_fields LIKE TABLE OF shlp_tab-fielddescr.
        DATA : w_fields LIKE LINE OF shlp_tab-fielddescr.
        DATA : l_fname TYPE dfies-lfieldname.
        IF lo_syuname <> sy-uname.  "means we were here before and ITAB is filled...fm retains its data values...unless refresh happens
    "this if condition make sure that we do not do this select all the time as long as the same user is logged in...
    "a user can press f4 many times...you might want to enhance this logic a little bit more for performance
          lo_syuname = sy-uname.
    ))))))))))))))HERE DO YOUR SELECT(((((((((((((((((((((
    select pernr from "sometable" into table itab.
        ENDIF.
        LOOP AT shlp_tab.
          LOOP AT shlp_tab-fielddescr INTO w_fields.
            l_fname = w_fields-fieldname.
            CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
              EXPORTING
                parameter               = w_fields-fieldname
              OFF_SOURCE              = 0
              LEN_SOURCE              = 0
              VALUE                   =
               fieldname               = l_fname
              TABLES
                shlp_tab                = shlp_tab
                record_tab              = record_tab
                source_tab              =  itab
              CHANGING
                shlp                    = shlp
                callcontrol             = callcontrol
             EXCEPTIONS
               parameter_unknown       = 1
               OTHERS                  = 2
          ENDLOOP.
        ENDLOOP.
        IF sy-subrc EQ 0.
          callcontrol-step = 'DISP'.
        ELSE.
          callcontrol-step = 'EXIT'.
        ENDIF.
        EXIT. "Don't process STEP DISP additionally in this call.
      ENDIF.
    4) save and activate this function module...
    5) go to se11 and create "Elementary srch hlp"....
    6) fill out all the necessary fields...i am assuming that you already know how to create the search helps...
    look for this field: "Search help exit" and put your function name which you created in the above steps...
    in this example i have: ZF4IF_SHLP_EXIT_pernr....
    7) create and activate the search help....
    hope this helps...i just tested this and it is working for me....
    Thanks..
    AS...

  • Help with JSTL sql query

    i have a query that i want to pass a paramater to the query goes like this
    <sql:query var = "user" >
    SELECT AMOUNT,flag FROM SAVINGS_ACTIVITY_DETAILS WHERE ACCOUNT_ID =? AND AMOUNT >200000 AND Flag =1 AND ACCOUNT_ACTION_ID =6 AND Treated =0 ORDER BY created_date DESC
    <sql:param value="${test.accountId}"/>
    </sql:query>
    this will give an error on TLD attribute.................and i tested the value with the following code and it worked
    <c:set value="${test.accountId}" var="u"/>
    <c:out value="${u}"/>
    this will print out the value nicely now i need a way to be able to pass this value to the sql query
    Thanks

    Which version of jstl are you using? == JSTL1.1
    However the other two questions remain unanswered.
    What server are you using? Version?
    How are you importing the tag library?
    You can find out the server info with this snippet of a JSP:
    Working with server: <%= application.getServerInfo() %><br>
    Servlet Specification: <%= application.getMajorVersion() %>.<%= application.getMinorVersion() %> <br>
    JSP version: <%= JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion() %><br>
    Java Version: <%= System.getProperty("java.version") %><br>

  • Help with translating SQL query from SQL Server syntax to Oracle syntax

    Hi,
    is it someone that can help me translate following SQL query from SQL Server syntax to Oracle syntax.
    SELECT ID,
    [LMT(MTR)] = MAX(case when TYPE = 'LMT' then VALUE end),
    [AAD(KGM)] = MAX(case when TYPE = 'AAD' then VALUE end),
    [VOL(MTQ)] = MAX(case when TYPE = 'VOL' then VALUE end)
    FROM yourtable
    GROUP BY ID
    Your help is highly appreciated, thanks in advance.

    Like this,
    SELECT ID,
    MAX(case when TYPE = 'LMT' then VALUE end) LMT_MTR,
    MAX(case when TYPE = 'AAD' then VALUE end) AAD_KGM ,
    MAX(case when TYPE = 'VOL' then VALUE end) VOL_MTQ
    FROM yourtable
    GROUP BY ID-Arun

  • Help with structuring SQL databases for multiple photo galleries..help!?!

    Hello all,
    As a new PHP/SQL developer I have found great technical assistance from both this forum and from David Powers and his wonderful books. I am at a crucial point in my web development and although I believe I know which direction I need to go, I am still uncertain and so I appeal to you all for your help, especially David Powers.
    The website I am building is one which will house many photo galleries. I was able to successfully modify the code provided in David Powers’ book ‘php Solutions’ so that I got the photo galleries constructed and working in the manner I desired.
    That being said, a person browsing my website will be presented with a link to see the photo galleries. There will be five (5) categories in which the photos will be separated, all based on specific styles. Now that I have the galleries working, I need to know how to structure things so that I can create a page, like a TOC (table o’ contents) that shows all photo galleries by displaying a thumbnail image or two along with the description. Perhaps I’ll limit the TOC page to only show the latest 25 galleries, arranged with the most current always on top.
    The way I have my galleries set up, I have a separate database for each one, containing the photo filenames and other relevant data. To build my TOC structure, should I have an overall database that contains each gallery database filename along with category? This is where I have no idea what I’m doing so if my question sounds vague, please understand I have no other idea how to ask.
    The site will grow to the point of having hundreds, if not thousands of photo galleries. I simply want to know how to (organize them) or otherwise allow me to build a method to display them in a TOC page or pages.
    I know this is a bit dodgy, but with some info and questions back from you, I feel confident that I should be able to get my point across.
    Lastly, I am still developing this site locally, so I have no links to provide (though I feel that shouldn’t be necessary right now).
    Many sincere thanks to you all in advance,
    wordman

    bregent,
    I'm chewing this over in my head, reading up on DB's in 'phpSolutions' and I think that things are slowly materializing.
    Here is the structure of the website that I have planned:
    MAIN PAGE
    User is presented with a link on the main page to select photo galleries (other links are also present). Clicking the link takes them to the Category Page.
    CATEGORY PAGE
    On this page, the User will then have 5 choices based on categories (photo style). CLicking any of these 5 links will take them to respective TOC pages.
    TOC PAGE
    On this page, the user is greeted with a vertical list of galleries or photosets; one to three thumbs on the left, a small block of descriptive text on the right (ideally containing date/time info to show how recent the gallery is). Newest galleries appear at the top. Eventually, when there are tens or hundreds of galleries in any given catrgory, I'll need to adopt a method for breaking up the qualntity in groups (we can pick 20 for example) that can be scrolled through using a small navbar. This will keep the TOC Pages from getting endlessly long and avoid endless scrolling. User selects a gallery on this page to view.
    THUMBNAIL PAGE
    On choosing a gallery, a thumbnail page is generated (I have this working already)
    IMAGE PAGE
    On selecting any thumbnail in the grid, the user is taken to the full-sized photo with a navbar and photo counter at the top. Navlinks allow forward and back, a link to the first image, a link to the last image and one link back to the thumbnail page. (I have this working already).
    I provide this info in an effort to help understand the basic structure of my site. The description above is as close to a step-by-step illustration as possible.
    Thank you!
    Sincerely,
    wordman

  • Need Help with Advanced SQL Query

    It's advanced for me, at least. I have three tables that I
    need to use:
    Product (product_id and product_title are the fields)
    shipRegion (shipRegion_ID)
    product_shipRegion_shipCharge (product_id, shipRegion_ID,
    primaryShipCharge, secondaryShipCharge)
    What I am trying to do is create a query that will look for
    two things:
    1. Any product that is listed in the
    product_shipRegion_shipCharge table that has a primary or secondary
    ship charge of $0.00 or is NULL.
    That part is easy:
    SELECT DISTINCT p.product_id, p.product_title
    FROM product p
    INNER JOIN product_shipRegion_shipCharge pss ON p.product_id
    = pss.product_id AND (pss.primaryShipCharge IS NULL OR
    pss.primaryShipCharge = 0 OR pss.secondaryShipCharge IS NULL OR
    pss.secondaryShipCharge = 0)
    WHERE p.display = 1
    AND p.price > 0
    It's this next part that's tricky for me:
    2. Get the product_id and product_title (from the product
    table) that does NOT have any entry in the
    product_shipRegion_shipCharge table.
    I'm guessing that I need to include some kind of LEFT JOIN in
    the above query to find out what all of the regions are (from the
    shipRegion table) and then see what's missing for each product in
    the product_shipRegion_shipCharge table, but I have no idea how to
    do it.
    Anyone?
    Josh

    This should be what the query would look like using the left
    join:
    SELECT product_table.product_id, product_table.product_title
    FROM product_table
    LEFT OUTER JOIN product_shipRegion_shipCharge
    ON product_shipRegion_shipCharge.product_id =
    product_table.product_id
    WHERE product_shipRegion_shipCharge. product_id IS NULL
    SQL Server's query optimizer will probably turn the '...IN
    (subquery)' or '...exists (subquery)' into this kind of execution
    plan on its own - depending on your table structures.

  • Help with the SQL Query: How to use case.

    Q:- I have written a query which will written the following output.
    C1 C2 C3
    a ---- b.1 ---- 1
    a ---- b.1 ---- 1
    a ---- b.1 ---- 2
    a ---- b.1 ---- 3
    a ---- b.1 ---- 3
    a ---- b.2 ---- 1
    a ---- b.2 ---- 2
    a ---- b.2 ---- 2
    a ---- b.3 ---- 1
    ac---- b.1 ---- 1
    ac---- b.1 ---- 2
    ac---- b.2 ---- 1
    ac---- b.2 ---- 2
    ac---- b.2 ---- 3
    ac---- b.2 ---- 3
    ac---- b ---- 1
    But i want the output to print in the following way. Please suggest.
    C1 C2 C3
    a ---- b.1 ---- 1
    ------------------2
    ------------------3
    a ---- b.2 ---- 1
    ------------------2
    a ---- b.3 ---- 1
    ac---- b.1 ---- 1
    ------------------2
    ac---- b.2 ---- 1
    ------------------2
    ac---- b.2 ---- 3
    ac---- b ---- 1
    Edited by: user555994 on Jan 18, 2011 1:42 AM
    Edited by: user555994 on Jan 18, 2011 1:43 AM

    Or may be
    SQL> ed
    Wrote file afiedt.buf
      1  WITH sample_data AS
      2    (SELECT 'a' C1,'b.1' C2, 1 C3 FROM dual UNION ALL
      3     SELECT 'a' C1,'b.1' C2, 1 C3 FROM dual UNION ALL
      4     SELECT 'a' C1,'b.1' C2, 2 C3 FROM dual UNION ALL
      5     SELECT 'a' C1,'b.1' C2, 3 C3 FROM dual UNION ALL
      6     SELECT 'a' C1,'b.1' C2, 3 C3 FROM dual UNION ALL
      7     SELECT 'a' C1,'b.2' C2, 1 C3 FROM dual UNION ALL
      8     SELECT 'a' C1,'b.2' C2, 2 C3 FROM dual UNION ALL
      9     SELECT 'a' C1,'b.2' C2, 2 C3 FROM dual UNION ALL
    10     SELECT 'a' C1,'b.3' C2, 1 C3 FROM dual UNION ALL
    11     SELECT 'ac' C1,'b.1' C2, 1 C3 FROM dual UNION ALL
    12     SELECT 'ac' C1,'b.1' C2, 2 C3 FROM dual UNION ALL
    13     SELECT 'ac' C1,'b.2' C2, 1 C3 FROM dual UNION ALL
    14     SELECT 'ac' C1,'b.2' C2, 2 C3 FROM dual UNION ALL
    15     SELECT 'ac' C1,'b.2' C2, 3 C3 FROM dual UNION ALL
    16     SELECT 'ac' C1,'b.2' C2, 3 C3 FROM dual UNION ALL
    17     SELECT 'ac' C1,'b' C2, 1 C3 FROM dual
    18     )
    19  SELECT
    20         NVL2(LAG(C1) OVER (PARTITION BY C1,C2 ORDER BY C1,C2,C3),NULL,C1) C1
    21        ,NVL2(LAG(C2) OVER (PARTITION BY C1,C2 ORDER BY C1,C2,C3),NULL,C2) C2
    22        ,C3
    23* FROM (SELECT DISTINCT c1,c2,c3 FROM sample_data)
    SQL> /
    C1 C2          C3
    a  b.1          1
                    2
                    3
    a  b.2          1
                    2
    a  b.3          1
    ac b            1
    ac b.1          1
                    2
    ac b.2          1
                    2
    C1 C2          C3
                    3
    12 rows selected.
    SQL>

  • Help with this SQL Query please

    How many garments has each dressmaker constructed? You should give the number of garments and the name, house number and post code of each dressmaker.
    tables; dressmaker contains D_NO, D_NAME, D_HOUSE_NO, D_POST_CODE
    garment contains STYLE_NO, DESCRIPTION, LABOUR_COST, NOTIONS
    quantities contains STYLE_Q, SIZE_Q, QUANTITY
    The question title is multitableJOINS
    I believe i have to use (garment.style_no=quantities.style_q) if it will work, im new to oracle & SQL so all the help i get i am grateful for, thankyou.

    Not to be a jerk, but this forum is really not intended for homework. Show a little effort, and try it out. Post some results, and maybe someone will help you out. Getting others to do your homework will not help you when you get out of school.

  • Help with rewriting the query for faster execution.

    Hello Everybody,
    We are on Version
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    I am trying to get data from tab1 where col8 is equal to ' ' at the same time If we 2 or 3 records matched on col1 and col2 with different dates(col3) i am only interested in getting one record with the least date....
    Here is the sample data...
    Col1 col2 col3 COL4 COl5 Col6 COL7 COL8 COL9
    12 1 17-JAN-13 1 5 7 9 1233333 25
    10 2 16-JAN-13 2 5 7 9 1233333 25
    10 2 14-JAN-13 2 5 7 9 1233333 25
    16 6 16-JAN-13 6 5 7 9 1233333 28
    16 6 09-OCT-12 5 5 7 9 1233333 29
    16 6 15-JAN-13 6 5 7 9 1233333 28
    17 5 09-OCT-12 5 5 7 9 1233333 29
    17 5 16-JAN-13 6 5 7 9 1233333 28
    17 5 10-OCT-12 5 5 7 9 1233333 29
    I am expecting output like this only should pull records...with min or least date
    Col1 col2 col3 COL4 COl5 Col6 COL7 COL8 COL9
    10 2 14-JAN-13 2 5 7 9 1233333 25
    16 6 09-OCT-12 5 5 7 9 1233333 29
    17 5 09-OCT-12 5 5 7 9 1233333 29
    Below query works and we have close to billion rows in a table but the where clause would filter out to 100 mill records.
    and i am trying to see if there is an effecient way of writing this....we have an index on COL3.
    Select col1,col2,col3,col4,col5,col6,col7,col8,col9 from(Selct of.,row_number() over (partition by col1,col2 order by col3 asc) as rnk
    from tabl of where of.col8 = '1233333') where rnk = 1*
    From the above query i get the below explain plan
    | Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time | Pstart| Pstop |
    | 0 | SELECT STATEMENT | | 1016M| 118G| | 13M (2)| 45:46:43 | | |
    |* 1 | VIEW | | 1016M| 118G| | 13M (2)| 45:46:43 | | |
    |* 2 | WINDOW SORT PUSHED RANK| | 1016M| 43G| 64G| 13M (2)| 45:46:43 | | |
    | 3 | PARTITION LIST SINGLE | | 1016M| 43G| | 1878K (3)| 06:15:47 | 4 | 4 |
    | 4 | TABLE ACCESS FULL | TAB1 | 1016M| 43G| | 1878K (3)| 06:15:47 | 4 | 4 |
    Predicate Information (identified by operation id):
    1 - filter("RNK"=1)
    2 - filter(ROW_NUMBER() OVER ( PARTITION BY "COL1","COl2" ORDER BY "COl3")<=1)
    17 rows selected
    Thanks In Advance!
    Edited by: 983949 on Jan 24, 2013 11:50 AM

    983949 wrote:
    Hello Everybody,
    I am trying to get data from tab1 where col8 is equal to ' ' at the same time.
    If we 2 or 3 records matched on col1 and col2 with different dates(col3)
    i am only interested in getting one record with the least date...
    Below query works and we have close to billion rows in a table but the where clause would filter out to 100 mill records.
    and i am trying to see if there is an effecient way of writing this....we have an index on COL3.
    Select col1,col2,col3,col4,col5,col6,col7,col8,col9
    from(Selct of.*,row_number() over (partition by col1,col2 order by col3 asc) as rnk
    from tabl of where of.col8 = '1233333') where rnk = 1
    Thanks In Advance!How do I ask a question on the forums?
    SQL and PL/SQL FAQ

  • Help with nestes sql query

    Hi,
    I am trying to do the following:
    SELECT b_cost-(stay_cost+p_sal+bc_sal+cs_sal+ms_sal)
         FROM
              (SELECT sum(b_cost) b_cost FROM b)
              (SELECT sum(cost) stay_cost FROM sl)
              (SELECT sum(sal) p_sal FROM p)
              (SELECT sum(sal) bc_sal FROM bc)
              (SELECT sum(sal) cs_sal FROM cs)
              (SELECT sum(sal) ms_sal FROM ms)
         );I cannot execute the query ...
    What am I doing wrong?
    thanks

    Did you try my code.. ?????
    it's work fine for me..
    with b
    as
    (select 1 b_cost from dual),
    sl as
    (select 1 cost from dual),
    p as
    (select 1 sal from dual),
    bc as
    (select 1 sal from dual),
    cs as
    (select 1 sal from dual),
    ms as
    (select 1 sal from dual)
    SELECT tb.b_cost-(ts1.stay_cost+tp.p_sal+tbc.bc_sal+tcs.cs_sal+tms.ms_sal)
    FROM
              (SELECT sum(b_cost) b_cost FROM b) tb,
              (SELECT sum(cost) stay_cost FROM sl) ts1,
              (SELECT sum(sal) p_sal FROM p) tp,
              (SELECT sum(sal) bc_sal FROM bc) tbc,
              (SELECT sum(sal) cs_sal FROM cs) tcs,
              (SELECT sum(sal) ms_sal FROM ms) tms
    TB.B_COST-(TS1.STAY_COST+TP.P_SAL+TBC.BC_SAL+TCS.CS_SAL+TMS.MS_SAL)
                                                                     -4
    1 row selected.aweiden option works too.. !!
    what oracle version do you have ????
    Edited by: dask99 on Oct 30, 2008 3:40 PM

  • Help with a SQL Query

    Per my clients requirement, they need to pull all patients  with two qualifying visits in the past 2 years. What I have now, I believe is just ones for the past year - looking on ways to better imporve the coding to pull this info.
    SET NOCOUNT ON
    DECLARE
    @StartDate DATETIME ,
    @EndDate DATETIME ,
    @groupby1 VARCHAR(60)
    SET @StartDate = ISNULL(NULL,'1/1/1900')
    SET @EndDate = ISNULL(NULL,'1/1/3000')
    SET @groupby1 = CONVERT(VARCHAR(60),'None')
    DECLARE @AgeDate DATETIME
    DECLARE @Year DATETIME
    DECLARE @EndRptDate DATETIME
    DECLARE @StartRptDate DATETIME
    SET @AgeDate = '12/31/' + CONVERT(VARCHAR , YEAR('12/31/2013'))
    SET @Year = CONVERT(VARCHAR , ( YEAR('12/31/2013') ))
    SET @StartRptDate = CONVERT(VARCHAR , ( '01/01/2013' ))
    SET @EndRptDate = CONVERT(VARCHAR , ( '12/31/2013' ))
    DECLARE @qmed INT
    DECLARE @qden INT
    DECLARE @qbh INT
    DECLARE @qsa INT
    DECLARE @qen INT
    DECLARE @qop INT
    SELECT @qmed = MedListsId FROM MedLists WHERE TableName = 'ProcedureCodeQualifier' AND Description = 'HCPC - MED'
    SELECT @qden = MedListsId FROM MedLists WHERE TableName = 'ProcedureCodeQualifier' AND Description = 'HCPC - DEN'
    SELECT @qbh = MedListsId FROM MedLists WHERE TableName = 'ProcedureCodeQualifier' AND Description = 'HCPC - BH'
    SELECT @qsa = MedListsId FROM MedLists WHERE TableName = 'ProcedureCodeQualifier' AND Description = 'HCPC - SA'
    SELECT @qen = MedListsId FROM MedLists WHERE TableName = 'ProcedureCodeQualifier' AND Description = 'HCPC - EN'
    SELECT @qop = MedListsId FROM MedLists WHERE TableName = 'ProcedureCodeQualifier' AND Description = 'HCPC - OP'
    IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
    DROP TABLE #Temp
    --- Return visits with HCPC Qualifier
    --- Per Clients requirement, patients aged 50 - 80 with at least 2 qualifying visits in the last 2 years.
    SELECT DISTINCT
    pv.PatientProfileId,
    pv.PatientVisitId,
    pv.Visit,
    ml.Description
    INTO #Temp
    FROM
    PatientVisitProcs pvp
    LEFT OUTER JOIN PatientVisit pv ON pv.patientvisitid = pvp.patientvisitid
    INNER JOIN PatientProfile pp ON pv.PatientProfileId = pp.PatientProfileId
    LEFT OUTER JOIN MedLists ml ON ml.Medlistsid = pvp.CPTProcedureCodeQualifierMId
    WHERE
    CPTProcedureCodeQualifierMId IN(@qmed, @qden, @qbh, @qsa, @qen, @qop)
    AND ISNULL(pvp.voided,0) = 0 --filter out voided visits
    AND pvp.DateOfServiceFrom >= @startdate AND pvp.DateOfServiceFrom < @enddate + 1
    AND DATEPART(Year , pv.visit) = DATEPART(Year , @EndRptDate) -- limit to visits in this year
    AND -- Filter on Age
    (('50' = '-1' AND '80' = '125') OR (CAST((DATEDIFF(DAY,pp.Birthdate,@AgeDate) /365.25) AS INT) BETWEEN ('50') AND ('80')))
    GROUP BY
    pv.PatientProfileId ,
    pv.PatientVisitId ,
    pv.Visit ,
    ml.Description
    HAVING
    COUNT(*) >= 2
    -- must have 2+ visits in last 2 years
    SELECT
    dbo.FormatName(pp.Prefix , pp.First , pp.Middle , pp.Last , pp.Suffix) AS Name ,
    pp.PatientId ,
    ISNULL(CONVERT(VARCHAR(20), pp.BirthDate, 101),'') AS Birthdate ,
    ( DATEDIFF(day , pp.Birthdate , @AgeDate) / 365.25 ) AS Age ,
    ISNULL(pp.Address1 , '') AS PatientAddr1 ,
    ISNULL(pp.Address2 , '') AS PatientAddr2 ,
    pp.Address1 + ' ' + ISNULL(pp.Address2 , '') AS PatientAddress ,
    ISNULL(pp.City , '') AS PatientCity ,
    ISNULL(pp.State , '') AS PatientState ,
    ISNULL(pp.Zip , '') AS PatientZip ,
    ISNULL(pp.Country , '') AS PatientCountry ,
    ISNULL(pp.Address1 , '') + ISNULL(' ' + pp.Address2 , '') + ISNULL(pp.City , '') + ISNULL(', ' + pp.State , '') + ISNULL(' ' + pp.Zip , '') AS PatientFullAddr ,
    ISNULL(dbo.formatphone(pp.phone1 , 1) , '') AS [Phone 1] ,
    ISNULL(pp.Phone1Type , ' ') AS [Phone 1 Type] ,
    ISNULL(dbo.formatphone(pp.phone2 , 1) , '') AS [Phone 2] ,
    ISNULL(pp.Phone2Type , ' ') AS [Phone 2 Type] ,
    ISNULL(dbo.formatphone(pp.phone3 , 1) , '') AS [Phone 3] ,
    ISNULL(pp.Phone3Type , ' ') AS [Phone 3 Type] ,
    pv.TicketNumber ,
    ISNULL(CONVERT(VARCHAR(20) , ( pv.Visit ) , 101) , '') AS [Visit] ,
    pv.Visit AS PatientVisit ,
    fac.ListName AS Facility ,
    doc.ListName AS Doctor
    FROM
    PatientVisit pv
    JOIN #Temp t ON pv.PatientVisitId = t.PatientVisitId
    INNER JOIN PatientProfile pp ON pv.PatientProfileId = pp.PatientProfileId
    INNER JOIN DoctorFacility fac ON pv.FacilityId = fac.DoctorFacilityId
    LEFT JOIN DoctorFacility doc ON pv.DoctorID = doc.DoctorFacilityID

    If I understand the problem correctly, this criterion 
    AND DATEPART(Year , pv.visit) = DATEPART(Year , @EndRptDate) -
    needs to be changed to
    AND pv.visit >=dateadd(year, -2, @EndRptDate) and pv.visit <= @EndRptDate 
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles

  • Help with an SQL query

    DB version : 10.2.0.4
    Below is a query which will get all tables in ALL schemas which has both YEAR_N and MONTH_N columns and generate the delete statements.
    SELECT 'delete from '||owner||'.'||table_name||' where (year_n=2008 and month_n<4) or (year_n=2007);'
    from dba_tab_cols dc
    where column_name IN ( 'YEAR_N' , 'MONTH_N')
    GROUP BY OWNER, TABLE_NAME
    HAVING COUNT (COLUMN_NAME) = 2
    order by owner ascWe have around 400 schemas in our DB and total generated DELETE statements are over 50,000. Is there any way i could get the string
    COMMIT;printed after every schema. I could actually just copy paste the COMMIT; string manually randomly. But is there a way i could do this from the above sql?

    A bit simpler/shorter:
    SELECT 'delete from '||owner||'.'||table_name||' where (year_n=2008 and month_n<4) or (year_n=2007);'||
                     decode(lead(owner) over (partition by owner order by owner),owner,'','COMMIT;')
    from dba_tab_cols dc
    where column_name IN ( 'YEAR_N' , 'MONTH_N')
    GROUP BY OWNER, TABLE_NAME
    HAVING COUNT (COLUMN_NAME) = 2
    order by owner asc;Explanation: When next owner is the same as current we do nothing, otherwise append 'COMMIT;'

Maybe you are looking for

  • Problem in enabling the selection screen

    Hi , I have problem in enabling the selection screen. i have radio button and based on the radio button i need to make the date field as mandatory. When i tried this with at selection screen on radio button group XXX, itu2019s not triggering. Could y

  • Bluetooth modem

    I've heard that for some reason there is no bluetooth modem script for the iPhone. I need a phone that I can use as a bluetooth modem to connect my mac to the internet. I know LG generally doesn't have good Mac support. Does anyone know of specific b

  • I want to buy a AdobeCloud Licence for a student.

    Can i buy a Student Licence with a individual email in the Adobe Account. or i must create a new one with my Student Email Adress...

  • Printer error ICC message what is wrong?

    Printer error ICC comes up when I try to print. What is wrong?

  • What number to use on redeem gift card

    Sounds silly, but I've got a prepaid gift card and none of the numbers on the back are correct when I enter them to redeem. There is a bar on the back of the card that looks like it should be scratched to reveal something underneath (FastCard logo pl