Select and join one month record

I receive a request from my customer . He want generate a total sales record for a month and those data stored in daily sales table and customer table.
tblcustomer-20140101
tblcustomer-20140102
tblcustomer-20140103
tblcustomer-20141231
tblsales-20140101
tblsales-20140102
tblsales-20140103
tblsales-20141231
is there anyway when user select month name from application(ex: April), it will choose all april record and join it together?

Hi kjleong,
Generally to say, it is not a good practice to store the same entity data individually for each day, there are many shortages, such as the problem you posted in this thread. You can put all of them into one table and tag them with a DATE column. Anyway
in this case, to achieve your requirement, you may refer the below stored procedure(SP).
CREATE PROC ProcGetSales
@Year VARCHAR(20),
@Month VARCHAR(20)
AS
DECLARE @Date DATE;
DECLARE @Days INT;
DECLARE @SqlStr NVARCHAR(MAX);
SET @Date = @Year+'-'+@Month+'-01';
SET @Days = DATEDIFF(DAY,@Date,DATEADD(MM,1,@Date)); --get the days of the specific month
create a temp table
CREATE TABLE #Temp
col1 int --you should put the columns after join in your real envrioment here
table join statement, put the join result into a temp table
I dont know the columns so I use * here and the join condition is just based on assumption
you should modify the statement basing on your real environment
SET @SqlStr= 'INSERT INTO #Temp SELECT * FROM [tblcustomer-WhichDay] tc JOIN [tblsales-WhichDay] ts ON tc.customerID = ts.customerID';
DECLARE @Counter INT = 1;
WHILE @Counter <= @Days --loop the tables named after the specific month
BEGIN
DECLARE @Sql NVARCHAR(MAX) = REPLACE(@SqlStr,'WhichDay',CONVERT(VARCHAR(8),CAST(@Year+'-'+@Month+'-'+LTRIM(STR(@Counter)) AS DATE),112));
EXEC sp_executesql @Sql;
SET @Counter = @Counter+1;
END
SELECT * FROM #TEMP
The SP is not ready to use, you have to make some modification basing on your real environment before it works.
If you have any question, feel free to let me know.
Best regards,
Eric Zhang
If you have any feedback on our support, please click
here.

Similar Messages

  • Select and join

    Hi
    I want to know when is good to do join between 2 tables
    or to do select and loop and in the loop select single
    When it good to use for all entries
    Thanks
    have a nice day

    Hi
    JOIN is faster to fetch the data from database tables provided they have some connecting fields in both tables
    for all entries
    The WHERE clause of the SELECT statement has a special variant that allows you to derive conditions from the lines and columns of an internal table:
    SELECT ... FOR ALL ENTRIES IN <itab> WHERE <cond> ...
    <cond> may be formulated as described above. If you specify a field of the internal table <itab> as an operand in a condition, you address all lines of the internal table. The comparison is then performed for each line of the internal table. For each line, the system selects the lines from the database table that satisfy the condition. The result set of the SELECT statement is the union of the individual selections for each line of the internal table. Duplicate lines are automatically eliminated from the result set. If <itab> is empty, the addition FOR ALL ENTRIES is disregarded, and all entries are read.
    The internal table <itab> must have a structured line type, and each field that occurs in the condition <cond> must be compatible with the column of the database with which it is compared. Do not use the operators LIKE, BETWEEN, and IN in comparisons using internal table fields. You may not use the ORDER BY clause in the same SELECT statement.
    You can use the option FOR ALL ENTRIES to replace nested select loops by operations on internal tables. This can significantly improve the performance for large sets of selected data.
    Select single and Upto 1 rows
    Difference Between Select Single and Select UpTo One Rows
    According to SAP Performance course the SELECT UP TO 1 ROWS is faster than SELECT SINGLE because you are not using all the primary key fields.
    select single is a construct designed to read database records with primary key. In the absence of the primary key, it might end up doing a sequential search, whereas the select up to 1 rows may assume that there is no primary key supplied and will try to find most suitable index.
    The best way to find out is through sql trace or runtime analysis.
    Use "select up to 1 rows" only if you are sure that all the records returned will have the same value for the field(s) you are interested in. If not, you will be reading only the first record which matches the criteria, but may be the second or the third record has the value you are looking for.
    The System test result showed that the variant Single * takes less time than Up to 1 rows as there is an additional level for COUNT STOP KEY for SELECT ENDSELECT UP TO 1 ROWS.
    The 'SELECT SINGLE' statement selects the first row in the database that it finds that fulfils the 'WHERE' clause If this results in multiple records then only the first one will be returned and therefore may not be unique.
    Mainly: to read data from
    The 'SELECT .... UP TO 1 ROWS' statement is subtly different. The database selects all of the relevant records that are defined by the WHERE clause, applies any aggregate, ordering or grouping functions to them and then returns the first record of the result set.
    Mainly: to check if entries exist.
    Reward points for useful Answers
    Regards
    Anji

  • How to select and sum  internal table records

    Dear Friends
    I kindly ask you if we have select statement
       if s_mtart = 'z003'
          select single pvprs from ckmlcr into ckmlcr-pvprs
    where poper EQ s_poper and
          kalnr = itab2-kalnr  and
          bdatj = itab2-bdatj and
          curtp = itab2-curtp.
    like this how can I calculate how many record it got and I want to get summation of this field(pvprs).And for all poper's must contain.
      Please  Let me remind you my itab is already open I didn't put any thing for this situation

    it seems to be you written this SELECT in a loop. if so,
    instead of pushing the values into ckmlcr-pvprs ,create an internal table
    data : begin of itab,
         pvprs  type ckmlcr-pvprs ,
        end of itab.
    then just after that SELECT SINGLE,
    select single pvprs from ckmlcr <b>into ITAB-pvprs</b>
    where poper EQ s_poper and
    kalnr = itab2-kalnr and
    bdatj = itab2-bdatj and
    curtp = itab2-curtp.
    IF SY-SUBRC = 0.
      APPEND ITAB.
    here either you can use APPEND OR COLLECT.
    If you use COLLECT,all the values will get summed up and final sum will be in the table ITAB-pvprs.
    ENDIF.
    After all loops your itab will have the totals.
    DESCRIBE TABLE ITAB LINES V_LINES.
    V_LINES Will have total no of lines.
    Regards
    srikanth

  • Selecting and joining differnent tables based on columns populated

    I have a table for audit purpose
    Table paudit
    pauditid (NOT NULL)
    operationid (NOT NULL)               
    typeid     (NOT NULL) -- Electronics, furniture, entertainment, department     
    operatorid (NOT NULL)
    electronicsid
    furnitureid
    entertainmentid                    
    departmentid               
    location (NOT NULL)
    changeto
    changefrom
    memberelectronicsid               
    memberfurnitureid               
    memberentertainmentid          
    memberdepartmentname     
    paudittime     
    deptfrom          
    deptto
    operatorname     name     type          operation     location     deptfrom     deptto     membername
    operatorname1     name1     Electronics     install          abcbcbcb
              name2     furniture     uninstall     nnddnd
              name3     furniture     move          jdjdj          abc          def
                   entertainment     product_add     gjhg                         adfgfgffdg
                   entertainment     product_del     gfhfghj                         dgfdfgdfgf
    Operatorname2As you can see, based on the typeid and operationid differnt columns get populated. But the proble is that is all these columnid's have to be joined to the resipective tables to get the names and the result will have be all consolidated into a single column. Like the column "name", in the sample above, to get the name, based on the type, would have to be joined with 4 differnt tables to get the "name". Based on the "operation" 3 diffent tables would have to joined to get the "membername". Hope this is clear.
    I was thinking about using "With as" and "parition by". But I got confused. So I would like some one to help me out if they have done something similar or point me in the right direction.
    Also these reports could be run for long periods of time or often and hence performance is also important.

    Well one of the main reason this was done was to enforce foreign keys when it comes to using ids and referring from other tables and the columns were split based on the produt type.
    pauditid     operationid     operatorid     electronicsid     furnitureid     entertainmentid     departmentid     location     changeto     changefrom     memberelectronicsid     memberfurnitureid     memberentertainmentid     memberdepartmentname     paudittime     deptfrom     deptto     typeid
    41     2     3     74                    UYWZrKifzeVVGJzhocmh                                                  1
    42     3     3          66               ngqmfBaagQyLMTXNjjju                                                  2
    43     2     13               9          NnLBvOJjZAPJFtkJLQcg                                                  3
    44     4     13                    16     NRYMhvySvbrsiuLKAgfH                                                  4
    45     2     7     10                    hZAMQcoGeeMXjrNcfBsH                                                  1
    46     4     50          11               vKswkxnfNnRkcKkFxanP                                                  2
    47     3     13               4          opBYnyQLArRwxOQTURww                                                  3
    48     1     22                    14     SaGoHjQGtlMQjjOzfFEO                                                  4
    49     4     41     53                    DaPXkQVAZOvqgWPXFlEi                                                  1
    108     1     13                    14     OfYVYvhBJpwExyfrIDux                                                  4
    109     4     6     81                    GODUpaejHEdpcOGTYGsF     iSHTF     aJtmf                                        1
    110     2     21          88               cpOVLkRuZtaMlLgKmCXz     MIMoN     NcFwD                                        2
    111     1     32               36          DyaqlSglgvDTzQMMQmsa     gipDq     bIoTb                                        3
    112     4     47                    48     ncwzqYjSCgIcBaeOxXkk     XVuZi     fEuYj                                        4
    113     1     33     62                    PzHlvjpYjJkPhFYfZDzN     ryVIB     tPHoA                                        1
    114     4     46          16               jnVNDWHuUnDAyOFItlaD     EoRsW     tkkYU                                        2
    115     4     43               45          lvJvmTYmQrwkNJnBirEX     MAFgG     xbqym                                        3
    116     4     25                    98     JtBYgfCSAoBafXbcovhr     yDstl     llGPL                                        4
    186     7     3               2          kvymkGFDPsPcqtRqmdFF                    32                              3
    187     8     18               6          YcwhKhgRdMlUspaLlGWj                         50                         3
    188     7     19               8          EGtVVpNJYuUunmUsEBxj                              jrCYkboqxXadjqDgWuaB                    3
    189     7     4               8          gcuEqHTTJspnohiLSNom               15                                   3
    190     8     12               13          KgvuLHNQLmHOruIzpNOR                    33                              3
    191     7     8               24          jjNJseqqIqzCPgkUfxBg                         55                         3
    192     8     6               5          bDEYJnZtQJEDlDHUcGQG                              bsTVKQxsQaGKmShBRPkZ                    3
    193     8     3               4          AkroIDSnEkfdlTCRZOfE               7                                   3
    241     9     8     19                    vbrGYWcdrTbCQdtGAVlZ                                        15     6     1
    242     9     7          13               AoKZgAtBkkvXqFwcpZQl                                        25     10     2
    243     9     16               14          CEKuwaMwPCfEXWecDXaG                                        17     20     3
    244     9     17                    20     uCLddsBDtVTdbGxAmbcN                                        14     14     4
    245     9     3     22                    wrsiJORxHWXaTNzIXziy                                        14     14     1
    246     9     14          20               zCULRoirtEMnHSAArrEu                                        10     24     2
    247     9     5               6          bKLEEijvtNuaCApBajNa                                        16     1     3
                                                                          

  • When i start Firefox two homepage open. First i have selected and other one is Noscript addons homepage. I want to remove Noscript homepage and want to set another website. How?

    FireFox start with two homepage.
    One set by me but another (Noscript homepage) want to edit (Remove).

    This article maybe help to you:
    * https://support.mozilla.com/en-US/kb/How%20to%20set%20the%20home%20page

  • How to select more than one data packet?

    Hi,
    I have uploaded data using 3 different data packets. However, for each of these packets there are some errors.
    Using Monitor > PSA Maintenance, I want to display error data records for all three different data packets in one screen. These erratic data will be send to our users for their rectification. However, I can only select and disply erratic data records packet by packet. So this has to be done three time instead of once.
    Can u advise on how to display all erratic data records in one screen.

    Hello Fulham FC,
    How r u ?
    I feel it is possible to select all 2 or more requests at once. Provide
    ...No. of Records ---> count the total no of records in the packages u select.
    ...From Record -
    > 2147483647
    Then try CONTINUE. In our system its throwing Dump !!!
    I believe dude, in PSA Maintenence there is a button  SELECT ALL & even in the data package also it is allowing to select two or more. There should be some way to do this.
    Best Regards....
    Sankar Kumar
    +91 98403 47141

  • Random selection of rows from a 2D array then subset both the rows that were selected and those that were not. Please see message below.

    For example, I have a 2D array with 46 rows and 400 columns. I would like to randomly select 46 data rows from the 2D array. By doing the random selection it means that not all individual 46 rows will be selected some rows may appear more than once as there may be some duplicates or triplicates in the random selection. The importan thing is that we will have randomly selected 46 rows of data (no matter that some rows appear more than once). Then I would like to subset these randomly selected 46 data rows (some which will be duplicated, or triplicated, etc.) and then also find and subset the rows that were not selected. Does this make sense? Then i would like to do this say 10 times for this data set. So that then I will have 2 by 10 data sets: the first 10 each with 46 rows and the other 10 with n rows depending on how many WERE NOT randomly selected. i hope that my explanation is clear. I am relatively new to Labview. It is really great so I am getting better! If anyone can help me with this problems it will be great. RVR

    Start by generating randon #s between 0 and 45. Run a for loop X times and in it use the random function, multiply the result by X and round down (-infinity). You can make this into a subVI, which you can reuse later. In the same loop, or in a different one, use Index Array to extract the rows which were selected (wiring the result out of the loop with auto indexing causes it to be rebuilt into a 2D array).
    One possible solution for the second part would be to go over the array of randomly generated numbers in a for loop and use Search 1D Array to find each of the numbers (i). If you get -1, it means the row wasn't selected and you can extract it.
    I hope this puts you on the right path. If not, don't be afraid to ask more.
    To learn more about LV, I suggest you read the LabVIEW user manual. Also, try searching this site and google for LabVIEW tutorials. Here and here are a couple you can start with. You can also contact your local NI office and join one of their courses.
    In addition, I suggest you read the LabVIEW style guide.
    Try to take over the world!

  • Why is Verizon charging me monthly for my cellular iPad access when I signed up for just one month? Who do I contact?

    I signed up for Verizon's month to month plan for cellular access and just discovered they are automatically renewing my monthly charges without my permission. Who and how can I contact Verizon to stop this and refund one month of unused cellular access? Please advise.

    Well then I stand corrected. I bought my iPad with a Verizon MIFI2200 WiFi hotspot directly from Verizon Wireless when they were running a promo last October. Verizon had just started selling the iPad and they came out with this deal and I took advantage of the offer. My plan is also a month to month access plan, but as far as I know, you still have to contact Verizon to stop the service. I know with my plan, unless I specifically cancel the plan, it carries over to the next month. The advantage to this plan is that there was no contract to sign and I can cancel at anytime without any early termination fee. However, I still have to cancel the service if I don't want it to continue.
    The bottom line is that the plan will continue month to month - there is just no contract to hold you to a two year agreement. You may have misunderstood or maybe you got bad information from the Apple rep, but what Verizon is doing is not being done without your permission - AFAIK. That is how month to month plans work.
    If you really feel that the Apple rep misrepresented this to you, then why don't you go back to him/the store - whatever and plead your case with him/her/the store?

  • ESB performance issue: takes too long to select and insert records in DBs

    Hi,
    I have an ESB service which has to select data from seven different tables(using join operations) of one database and insert it into a single table of another database.
    It takes unduly long time to do this operation.
    For ex: it takes over 2 hours to select and insert 3000 records.
    When ran the same query to select the records from the tables using SQL developer, it took only 23 seconds.
    Do I need to change any configuration settings in the enterprise manager or someother place to increase the performance. Someone please advice.
    I am using Oracle SOA Suite 10.1.3.4
    Thanks,
    RV

    Hi,
    I have an ESB service which has to select data from seven different tables(using join operations) of one database and insert it into a single table of another database.
    It takes unduly long time to do this operation.
    For ex: it takes over 2 hours to select and insert 3000 records.
    When ran the same query to select the records from the tables using SQL developer, it took only 23 seconds.
    Do I need to change any configuration settings in the enterprise manager or someother place to increase the performance. Someone please advice.
    I am using Oracle SOA Suite 10.1.3.4
    Thanks,
    RV

  • Missing LO changes and creations since one month

    Hi
    We have some issues with our LO data source and now the issue has been resolved. We need to delete the requests since one month
    and reload. We have the following date selections available in the info pakcage Createdon and changed on. Can we load all the
    changes and new creation during that time with this selctions without getting duplicates ?
    Please advice

    Hi,
    created on load part is fine as you said and you should do that but
    then load the data changed between those two dates
    this part will create issue as it will send records to cube which are already present in the cube since they can have created on dates in the past.
    created on load part is fine as you said and you should do that.
    I mean....same record can have created on and changed values
    created on is static and will never change...so a record created in 01.01.1900 will not come in your selection based on created on but it is still present in the cube.
    now if the same record got changed in the last one month..i.e. the time when the delta was not working...if you give the changed on selection then it will bring the same record again...and may be if your load goes for two days then for the third time as well if it gets changed on last loading day...
    some thing like you loaded for the selection
    first you loaded created on 01.01.1900-31.09.2008
    then changed on 01.10.2008- 02.12.2008
    Now there is one record which as created on date as 01.01.1900...and changed on date as 02.10.2008...and if the old record is not deleted from the cube then it will get doubled. after load based on changed on
    also if the load keep on running for two days and is the same record got changed on 03.12.2008 then it will come thrice.
    So in any case you will have to delete the history from the cube to load the data correctly.
    Thanks
    Ajeet

  • Join two Connect By Prior Start With trees and return only common records?

    Oracle 10g Release 2 (10.2)
    I have two tables that have tree structured data. The results, when running the queries individually are correct, however I need to join tree one to tree two in order to obtain only the common records between them.
    -- Tree one
    SELECT ip_entity_name, entity_code, hier_level, entity_parent
    FROM ip_hierarchy
    WHERE hier_level >= 3
    CONNECT BY PRIOR entity_code = entity_parent
    START WITH entity_code = 'MEWWD';
    -- Tree two
    SELECT ip_entity_name, entity_code, hier_level, entity_parent
    FROM ipt_hierarchy
    WHERE hier_level >= 3
    CONNECT BY PRIOR entity_code = entity_parent
    START WITH entity_code = 'IPNAM';
    As I understand, joins may not work with CONNECT BY/START WITH queries?
    Is a WITH clause an option?
    If at all possible, I don't want to put one select in a View database object and join against the other query.
    Thanks.

    Hi JTP51,
    You can use WITH clause or sub-query by using in-line view, without creating any view object in database.
    for example
    SELECT A.IP_ENTITY_NAME, A.ENTITY_CODE, ....
      FROM (SELECT IP_ENTITY_NAME, ENTITY_CODE, HIER_LEVEL, ENTITY_PARENT
              FROM IP_HIERARCHY
             WHERE HIER_LEVEL >= 3
            CONNECT BY PRIOR ENTITY_CODE = ENTITY_PARENT
             START WITH ENTITY_CODE = 'MEWWD') A,
           (SELECT IP_ENTITY_NAME, ENTITY_CODE, HIER_LEVEL, ENTITY_PARENT
              FROM IPT_HIERARCHY
             WHERE HIER_LEVEL >= 3
            CONNECT BY PRIOR ENTITY_CODE = ENTITY_PARENT
             START WITH ENTITY_CODE = 'IPNAM') B
    WHERE A. ENTITY_CODE = B. ENTITY_CODE
    AND ....Best regards,
    Zhxiang
    Edited by: zhxiangxie on Feb 2, 2010 5:35 PM

  • Using combination of insert into and select to create a new record in the table

    Hello:
    I'm trying to write a stored procedure that receives a record locator parameter
    and then uses this parameter to locate the record and then copy this record
    into the table with a few columns changed.
    I'll use a sample to clarify my question a bit further
    -- Create New Amendment
    function create_amendment(p_mipr_number in mipr.mipr_number%TYPE, p_new_amendment_number in mipr.amendment_number%TYPE)
    return integer is
    new_mipr_id integer;
    begin
    THIS is causing me grief See comments after this block of code
    insert into mipr
    (select mipr_id from mipr where mipr_number=p_mipr_number),
    (select fsc from mipr where mipr_number=p_mipr_number),
    45,
    (select price from mipr where mipr_number=p_mipr_number),
    practical,
    (select part_number from mipr where mipr_number=p_mipr_number);
    THe above will work if I say the following
    insert into mipr
    (select * from mipr where mipr_number=p_mipr_number);
    BUt, Of course this isn't what I want to do... I want to duplicate a record and change about 3 or 4 fields .
    How do I use a combination of more than one select and hard coded values to insert a new record into the table.
    /** Ignore below this is fine... I just put a snippet of a function in here ** The above insert statement is what I need help with
    select (mipr_id) into new_mipr_id from mipr where mipr_number=p_mipr_number + amendment_number=(select max(amendment_number) + 1);
    return new_mipr_id;
    end;
    THANK YOU IN ADVANCE!
    KT

    function create_amendment(p_mipr_number in mipr.mipr_number%TYPE)
    return integer is
    new_mipr_id integer;
    tmp_number number;
    tmp_mipr_id integer;
    begin
    tmp_number :=(select max(amendment_number) from mipr where mipr_number=p_mipr_number);
    Question:
    tmp_number :=1; works..
    tmp_number doesn't work with the select statement?
    Obviously I'm a novice! I can't find anything in my book regarding tmp variables... What should I look under is tmp_number a
    variable or what? In my Oracle book, variable means something different.
    Thanks!
    KT
    I have the following code in my stored procedure:
    Good luck,
    Eric Kamradt

  • How can i select more than one record in a LOV

    I want to select more than one record in a LOV and put them together before to display them in an item.

    This is not possible with a default LOV, so you'll need to create your own. There are a number of ways to select multiple records:
    a) you can use a tree and set Multi-Selection to Yes
    2) you can use a normal block with a checkbox on each row for the user to select records
    three) with the [SYSTEM.MOUSE_BUTTON_MODIFIERS|http://www.oracle.com/webapps/online-help/forms/10g/topics/designing_forms/mouse/at0604.html?tp=true] variable you can allow users to ctrl+click to select many records in a block. set the background colour to indicate a record has been selected
    iv) there is a pjc in the [demo code section|http://download.oracle.com/otndocs/demos/Forms_Demos_10gr2.zip] which lets you select many rows in a poplist

  • SELECT, hierarchical queries and JOIN

    Hi everyone,
    I have a small SELECT statement but I can't find an easy solution.
    Look at this situation:
    drop table departments;
    CREATE TABLE departments
      dpt_id NUMBER(10) UNIQUE,
      dpt_name VARCHAR2(100),
      dpt_parent_id NUMBER(10)
    TRUNCATE table departments;
    INSERT INTO departments VALUES(1, 'Company', null);
    INSERT INTO departments VALUES(2, 'HR', 1);
    INSERT INTO departments VALUES(3, 'SALES', 1);
    INSERT INTO departments VALUES(4, 'IT', 1);
    INSERT INTO departments VALUES(222, 'Helpdesk', 4);
    INSERT INTO departments VALUES(223, 'French Speaking', 222);
    INSERT INTO departments VALUES(224, 'Another level', 223);
    INSERT INTO departments VALUES(5, 'LEGAL', 1);
    INSERT INTO departments VALUES(66, 'Recruitment', 2);
    INSERT INTO departments VALUES(33, 'Logistics', 2);
    INSERT INTO departments VALUES(39, 'Fleet management', 33);
    INSERT INTO departments VALUES(31, 'Local Sales', 3);
    INSERT INTO departments VALUES(60, 'European Sales', 3);
    INSERT INTO departments VALUES(61, 'Germany', 60);
    INSERT INTO departments VALUES(62, 'France', 60);
    INSERT INTO departments VALUES(620, 'Paris', 62);
    INSERT INTO departments VALUES(621, 'Marseilles', 62);
    INSERT INTO departments VALUES(38, 'American Sales', 3);
    INSERT INTO departments VALUES(34, 'Asian Sales', 3);
    CREATE table persons
      person_id NUMBER(10) UNIQUE,
      person_name VARCHAR2(100),
      person_dpt_id NUMBER(10)
    truncate table persons;
    INSERT INTO persons VALUES(1, 'Jim', 2);
    INSERT INTO persons VALUES(2, 'Jack', 621);
    INSERT INTO persons VALUES(3, 'John', 620);
    INSERT INTO persons VALUES(4, 'John', 224);
    INSERT INTO persons VALUES(5, 'Fred', 61);It's a simple hierachy like the one we can find in HR schema. The link between an department and its parent is with parent id. THe following statement build the whole tree:
    SELECT dpt_id, level, LPAD(' ', LEVEL-1)|| dpt_name
      FROM departments
    START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id;As you can see in the script above, I have a few people assigned to these departments. It's also a classic situtation...
    I would like to have something like this:
    WITH temp AS
      SELECT dpt_id, dpt_name, SYS_CONNECT_BY_PATH(dpt_name, '#') as full_path
        FROM departments
       START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id
    SELECT p.person_name, d.dpt_name, --d.full_path,
           regexp_substr(d.full_path, '[^#]+', 1, 2, 'i') as t1,
           regexp_substr(d.full_path, '[^#]+', 1, 3, 'i') as t2,
           regexp_substr(d.full_path, '[^#]+', 1, 4, 'i') as t3,
           regexp_substr(d.full_path, '[^#]+', 1, 5, 'i') as t4
      FROM persons p
      JOIN temp d ON d.dpt_id = p.person_dpt_id;This is the exact output I want, but I wonder... Is it possible to do it without the factored sub-query? It's nice and works fine but I had to precompute the whole path to split it again. I mean, this should be possible in one step. Any suggestion?
    I'm using Oracle 10g
    Thanks,

    Hi,
    user13117585 wrote:
    ... But sometimes, I just find the statements difficult for what they do. For example, my previous one. I have a person, and I want to see his department and the path in the tree.Actually, you want more than that; you want to parse the path, and display each #-delimited part in a separate column. If you didn't want that, then you could do away with the 4 REGEXP_SUBSTR calls, like this:
    WITH temp AS
      SELECT dpt_id, dpt_name
      ,       SUBSTR ( REPLACE ( SYS_CONNECT_BY_PATH ( RPAD (dpt_name, 15)     -- Using 15 just for demo
               , 16
               )     as full_path
        FROM departments
       START WITH dpt_parent_id IS NULL
    CONNECT BY dpt_parent_id = PRIOR dpt_id
    SELECT p.person_name, d.dpt_name, d.full_path
      FROM persons p
      JOIN temp d ON d.dpt_id = p.person_dpt_id;Output:
    PERSON_N DPT_NAME      FULL_PATH
    Jim      HR            HR
    Fred     Germany       SALES          European Sales Germany
    John     Paris         SALES          European Sales France         Paris
    Jack     Marseilles    SALES          European Sales France         Marseilles
    John     Another level IT             Helpdesk       French SpeakingAnother levelAs you can see, full_path is one giant column, but it's formatted to look like 4 separate columns, forresponding to your original t1, t2, t3 and t4. I limited the output to 15 characters, just for debugging and posting purposes. You can use any number of characters you like.
    It's too complex for this simple thing.It would be nice if there was something simpler that did exactly what you wanted, but I'm not sure it's reasonable to expect it in every case. I asked a lot of questions in my first message, but I'm not sure you've tried to answer any of them, so I'm not sure why you're unhappy with the query you posted. I can think of lots of ways to change the query, but I have no way of telling if you would like them any better than what you already have.
    And hopefully, I know where to start in the hierarchy and I know where to stop. If I had to show all the levels and have one column by level dynamically, I'd be stuck. Sorry, I don't understand this part.
    Are you saying that it seems inefficient to generate the entire tree, when perhaps few of the nodes will have have matches in the persons table? If so, you can invert the whole query. Instead of doing the CONNECT BY first and then joining, do the join first and then the CONNECT BY. Instead of doing a top-down CONNECT BY, where you start with the parentless nodes (whether or not you'll ultimately need them) and then find their descendants, do a bottom-up CONNECT BY, where you start with the nodes you know you'll need, and then find their ancestors.
    I just find it difficult for such a simple need. Again, there are lots of things that could be done. If you won't say what you want, that makes it hard for me to tell you how to get it. All that I've picked up for sure is that you don't like doing a sub-query. That's unfortunate, because sub-queries are so basic. They have very important been since Oracle 8.1, and they don't seem to be going away. Quite the opposite, in fact. You need sub-queries for all kinds of things, not just CONNECT BY. To give just a couple of examples, they're the only thing that make analytic functions really useful, and they simplfy chasm traps (basically, multiple 1-to-many relationships on the same table) considerably. I'm sorry if you don't lke sub-queries, but I don't see how you can work in this field and not use them.
    Edited by: Frank Kulash on Nov 15, 2011 3:18 PM
    Revised query

  • Problem selecting MAX YEAR MAX MONTH MAX DATE in one query

    CREATE TABLE TEMP
    C_INVOICE_ID NUMBER(10),
    DIA NUMBER,
    MES NUMBER,
    ANO NUMBER,
    SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
    PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
    M_PRODUCT_ID NUMBER(10),
    CATEGORIA NVARCHAR2(60) NOT NULL,
    COSTO NUMBER
    INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
    INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
    INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
    INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
    INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
    INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
    INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
    INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
    INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
    INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
    INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
    INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
    INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
    INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    CREATE TABLE TEMP
    C_INVOICE_ID NUMBER(10),
    DIA NUMBER,
    MES NUMBER,
    ANO NUMBER,
    SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
    PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
    M_PRODUCT_ID NUMBER(10),
    CATEGORIA NVARCHAR2(60) NOT NULL,
    COSTO NUMBER
    INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
    INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
    INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
    INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
    INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
    INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
    INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
    INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
    INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
    INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
    INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
    INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
    INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
    INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    I have this query so far,
    SELECT
    MAX (TEMP.COSTO) COSTO,
    TEMP.M_PRODUCT_ID,
    TEMP.ANO
    FROM TEMP TEMP
    INNER JOIN(
    SELECT MAX(ANO) ANO, M_PRODUCT_ID
    FROM TEMP I
    GROUP BY M_PRODUCT_ID
    ) LA ON LA.ANO = TEMP.ANO AND LA.M_PRODUCT_ID = TEMP.M_PRODUCT_ID
    GROUP BY
    TEMP.M_PRODUCT_ID,
    TEMP.ANO
    but my intention is not to have the max cost, my intention is to query in this order
    first i need to select distinct m_product_id then
    for every m_product_id i need to
    filter max (ano) then filter max (mes) then filter max (dia)
    I need the result set like this.
    C_INVOICE_ID DIA MES ANO SOCIO PRODUCTO_NOM M_PRODUCT_ID CATERGORIA COSTO
    1015 15 2 2010 1520 ALURON 100MG X 30 TABLETAS 1530 15 2.15
    5654 5 2 2010 1520 AMARYL 2MG X 15 TABLETAS 1531 15 4.2
    15132 25 9 2010 1585 AMOXAL 250MG X 75ML SUSPENSION 1534 15 3.4
    please i really apritiated any help, thanks pd:i'm using oracle 9i

    Hi,
    Thanks for posting the CREATE TABLE and INSERT statements. Why are there two tables, and two sets of data? Was that a mistake?
    Sorry, I don't uderstand the problem.
    For m_product_id=1531, for example, why do you want
    INSERT INTO TEMP VALUES(5654,     5, 2, 2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);selected, and not
    INSERT INTO TEMP VALUES(116544,     8, 8, 2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);Both rows have ano=2010, so don't you want the one with the higher mes (8 > 2)?
    I think what you'll want is a Top-N Query , something like this:
    WITH     got_r_num     AS
         SELECT     temp.*     -- or list columns you want
         ,     RANK () OVER ( PARTITION BY  m_product_id
                          ORDER BY          ano     DESC     NULLS FIRST
                          ,          mes     DESC     NULLS FIRST
                          ,          dia     DESC     NULLS FIRST
                        )          AS r_num
         FROM     temp
    --     WHERE     ...     -- any filtering goes here
    SELECT     *     -- or list all columns except r_num
    FROM     got_r_num
    WHERE     r_num     = 1
    ;What if there's a tie? For example, if you add another row to the sample data:
    INSERT INTO TEMP VALUES(9876,     15,2, 2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);The query above would include both c_invoice_id=9876 and 1015. If you want just one of those rows, add more expressions to the analytic ORDER BY clause and/or use ROW_NUMBER instead of RANK.

Maybe you are looking for