Best way to flatten out this table?

Lets say you're dealing with these two tables:
CREATE TABLE VEHICLES
VEHICLE_ID NUMBER,
VEHICLE_NAME VARCHAR2(100 BYTE),
MILES NUMBER
CREATE TABLE VEHICLE_PARTS
PART_ID NUMBER,
VEHICLE_ID NUMBER NOT NULL,
PART_TYPE NUMBER NOT NULL,
PART_DESCRIPTION VARCHAR2(1000 BYTE) NOT NULL,
START_SERVICE_DATE DATE NOT NULL,
END_SERVICE_DATE DATE,
PART_TYPE_NAME VARCHAR2(100 BYTE)
And some example data as follows:
Insert into VEHICLES (VEHICLE_ID, VEHICLE_NAME, MILES) Values (1, 'Honda Civic', 75500);
Insert into VEHICLES (VEHICLE_ID, VEHICLE_NAME, MILES) Values (2, 'Ford Taurus', 156000);
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, END_SERVICE_DATE, PART_TYPE_NAME)
Values
(1, 1, 1, '1.4 VTEC',
TO_DATE('07/07/2009 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('05/03/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ENGINE');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, PART_TYPE_NAME)
Values
(2, 1, 1, '1.6 VTEC',
TO_DATE('05/03/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ENGINE');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, END_SERVICE_DATE, PART_TYPE_NAME)
Values
(3, 1, 2, 'Good Year All-Season',
TO_DATE('07/07/2009 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('08/10/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'TIRES');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, PART_TYPE_NAME)
Values
(4, 1, 2, 'Bridgestone Blizzaks',
TO_DATE('08/10/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'TIRES');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, PART_TYPE_NAME)
Values
(5, 2, 1, '3.5 L Duratec',
TO_DATE('06/01/2008 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ENGINE');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, END_SERVICE_DATE, PART_TYPE_NAME)
Values
(6, 2, 2, 'Good Year All-Season',
TO_DATE('06/01/2008 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('03/15/2009 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'TIRES');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, END_SERVICE_DATE, PART_TYPE_NAME)
Values
(7, 2, 2, 'Michelin All-Seaon',
TO_DATE('03/15/2009 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('01/12/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'TIRES');
Insert into VEHICLE_PARTS
(PART_ID, VEHICLE_ID, PART_TYPE, PART_DESCRIPTION, START_SERVICE_DATE, PART_TYPE_NAME)
Values
(8, 2, 2, 'Nokian',
TO_DATE('01/12/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'TIRES');
And you need to produce a view which displays the joined data flattened out where each vehicle has one row with columns representing their most current part (by what has a service start date with null end date).
Like this:
Vehicle: Engine: Tires:
Honda Civic 1.6 VTEC Bridgestone Blizzaks
Ford Taurus 3.5 L Duratec Nokian
Is there a fast/efficient way to do this?
My current approach which is the brute force method is to have a separate outer join for each column I need to pull with condition of max(START_SERVICE_DATE) to get the current part for each type (Engine, Tires, etc...).
but its so slow and painful code.
i thought about Pivot but I dont think Pivot would help here since there is no aggregation going on, right?
Could anything with partition over help? Im not familiar with that syntax

Hi,
trant wrote:
Your query does work great I just ran it - but by your last note about wanting to use SELECT...PIVOT - would you please elaborate on that?If you're used to doing pivots with CASE (or DECODE) and GROUP BY, then you may require some practice before the new way seems better. I beliieve it is, and I think you'll find whatever effort you have to spend in learning to use the new PIVOT feature is time well invested. I find this code:
WITH     got_r_num     AS
     SELECT     v.vehicle_name
     ,     vp.part_description
     ,     vp.part_type_name
     ,     ROW_NUMBER () OVER ( PARTITION BY  vp.vehicle_id
                         ,             vp.part_type_name
                         ORDER BY        start_service_date
                       )     AS r_num
     FROM     vehicle_parts     vp
     JOIN     vehicles     v     ON     v.vehicle_id     = vp.vehicle_id
     WHERE     vp.end_service_date     IS NULL
SELECT       vehicle_name, engine, tires
FROM       got_r_num
PIVOT       (     MIN (part_description)
       FOR     part_type_name  IN ( 'ENGINE'     AS engine
                         , 'TIRES'     AS tires
WHERE       r_num     = 1
ORDER BY  vehicle_name
;easier to understand and maintain, and this is a more complicated than average example. Often, when using SELECT ... PIVOT, the main SELECT clause is juSt "SELECT *", and adding more columns is even easier. For eaxample:
WITH     got_r_num     AS
     SELECT     v.vehicle_name
     ,     vp.part_description
     ,     vp.part_type_name
     ,     ROW_NUMBER () OVER ( PARTITION BY  vp.vehicle_id
                         ,             vp.part_type_name
                         ORDER BY        start_service_date
                       )     AS r_num
     FROM     vehicle_parts     vp
     JOIN     vehicles     v     ON     v.vehicle_id     = vp.vehicle_id
     WHERE     vp.end_service_date     IS NULL
,     top_1_only     AS
     SELECT     vehicle_name
     ,     part_description
     ,     part_type_name
     FROM     got_r_num
     WHERE     r_num     = 1
SELECT       *
FROM       top_1_only
PIVOT       (     MIN (part_description)
       FOR     part_type_name  IN ( 'ENGINE'
                         , 'TIRES'
ORDER BY  vehicle_name
;If you want to include BRAKES and STEERING columns, all you have to do is change
FOR     part_type_name  IN ( 'ENGINE', 'TIRES')to
FOR     part_type_name  IN ( 'ENGINE', 'TIRES', 'BRAKES', 'STEERING')The only way it could be any easier is if it were automatic! (That's another subject entirely.)

Similar Messages

  • Best way to lay out this scrapbook

    I need some advice about the best way to go about this. I have a client who basically want me to publish her scrapbook. It's full of all sorts of color and b/w photos, drawings, newspaper clippings, you name it. I was thinking I should scan each page (8 1/2 x 11) as a separate pdf, then place each pdf as a separate page in the ID document. After about 10 pages or so the ID document is so bogged down that it takes half a minute just to nudge a frame. I hate to think of what things would be at 200 pages. Even if I divided the book up into 20 or 40 separate documents then reassembled them as a book, it would probably be so unwieldy that I wouldn't even be able to scroll the pages. Once this is done it has to be submitted to the printer as a pdf.

    What the client has done is lay out her original photos on a piece of 8 1/2 x 11, xerox it, then type captions next to the xeroxed photos, then attach the original photos over the top of the xeroxes. Two pages are then placed back to back in a clear plastic sleeve, which, along with another 199 sleeves, goes into a ring binder. I’m laying the book in ID (CS3, btw) because I want to add page numbers and some of the pages need to be centered or otherwise moved around so that I can maintain the printer’s minimal margins (the typing and placement of the illustrations on the original page sometimes goes to the very edge). Also, as I scan I'm trying to cut out toner shadows and other blemishes on the original pages. I’ve been scanning using my scanner’s software (Epson Perfection V200). The setting for the image quality of the outputted scan is 24-bit color at 300 dpi (pages with just text are scanned as black & white, 300 dpi, pages with only black & white photos are scanned as grayscale). If I want to do more editing (like cleaning up more blemishes) I open the pdfs in Photoshop. That way I can also change the color mode to CMYK before I save the file. Should I be scanning directly into Photoshop, then? I don’t scale the pdfs in ID because I know that can affect the resolution. I’ll try making tifs instead of pdfs.

  • Best way to deal with Mutating table exception with Row Level Triggers

    Hello,
    It seems to be that the best way to deal with Mutating Table exception(s) is to have to put all the trigger code in a package & use it in conjunction with a Statement level trigger .
    This sounds quite cumbersome to me . I wonder is there any alternative to dealing with Mutating table exceptions ?
    With Regards

    AskTom has a good article about this,
    http://asktom.oracle.com/tkyte/Mutate/index.html

  • Best way to process out-of-gamut colors

    Hi,
    My usual colorspace whilst processing RAW images is Srgb, mainly because I print most shots & my printer requires Srgb for this.
    The problem is that I experience "out-of-gamut" warnings within ACR and would appreciate some advice on the best way to deal with this - my options seem to be:
    continue in Srgb & allow color to be clipped
    swap to a wider colorspace (lab/Argb), process the image & tthen convert to Srgb for print
    Ultimately though I need to output in Srgb so does it make any difference processing in the wider space as I guess the out-of-gamut color is going to be clipped at some stage anyway ?
    thanks for any advice
    Simon

    simonkit wrote:
    My usual colorspace whilst processing RAW images is Srgb, mainly because I print most shots & my printer requires Srgb for this.
    The problem is that I experience "out-of-gamut" warnings within ACR and would appreciate some advice on the best way to deal with this - my options seem to be:
    What printer are you using? Printers are nonlinear devices and as far as I know, no printer has sRGB as its native color space. Some printing services such as those offered by Walgreen and Walmart expect the image to be in sRGB and then convert behind the scenes to the native printer space. Walgreen often uses the Fuji Frontier and expects sRGB input. Some labs that cater to serious users will give you profiles for the Frontier. Some Costco stores use the Frontier and profiles are available on DryCreek.com. As Mylenium has pointed out in general for printers, the gamut of the Frontier is smaller than sRGB. However, their shapes are different and many colors in the sRGB gamut are not in the Frontier gamut. Conversely, a few colors in the printer gamut are outside of the Frontier gamut.
    Here is a 3D gamut plot of sRGB in solid color and a Fuji Frontier printer from a lab in my area shown as a wireframe. The gamut of sRGB is wider in the blues and magentas and these colors that fit in sRGB would be clipped on output to this printer and you would have no way of knowing that in the absence of a profile for the printer. A few yellows in the gamut of the printer are outside the gamut of sRGB, and these could have been saved if you had used a wider space such as aRGB or ProPhotoRGB.
    My suggestion is that you find a printer for which a profile is available. Costco uses Frontiers and Noritsus and makes profiles available. Most high end labs will give you a profile (otherwise, you are being ripped off). Then you can use soft proofing to detect and map out of gamut colors. If you are in aRGB and soft proof to see what colors are clipped in sRGB, you still do not know what colors that fit in sRGB would be clipped in printing. Also, if you have a profile with perceptual rendering (such rendering is not available for matrix profiles such as sRGB, aRGB, and ProPhotoRGB) you could try that to map the out of gamut colors.
    The most recent inkjets have a considerably wider gamut than photo paper, and the use of ProPhotoRGB is recommended for use with these.

  • We have always used one iTunes account and I want to crate a new account for my daughter.  What is the best way to go about this and will she need to download free apps again?

    We have always used one iTunes account and I want to crate a new account for my daughter.  What is the best way to go about this and will she need to download free apps again?

    Not going to happen the way you want it to.
    When you add a gift card balance to the Apple ID, it's available for the Apple ID.
    Probably best to create unique Apple ID's for each... this will also make things easier in the future as purchases are eternally tied to the Apple ID they were purchased with.

  • I am giving away a computer, what is the best way to wipe out data prior to depature

    i am giving away a computer, what is the best way to wipe out data prior to depature

    Did the Mac come with two grey disks when new? If so, use disk one to erase the drive using Disk Utility and then re-install the OS from the same disk. Once installed, quit and when the new owner boots they can set it up as a new out-of-the-box Mac when they boot it up. The grey disks need to be passed on with the computer.
    If you need detailed instructions on how to erase and re-install please post back.
    If the Mac came with Lion or Mountain Lion installed the above process can be done using the Recovery HD as since Lion no restore disks are supplied with the Mac.
    The terms of the licence state that a Mac should be sold/passed on with the OS installed that was on the machine when new (or words to that effect).

  • Best way to fade out multiple tracks at the same level

    Is there a best way to fade out multiple tracks at the end of a song? I have read the manual and understand fading "A" track, but not if my song is ending and I want to fade out all tracks equally.
    I thought I could export the file as a wav or MP3 (like I would do if I was fading out an Apple loop), then bring it back in and fade the track I import it to, but wanted to know if anyone else had any tips or tricks they use.
    Thanks
    RH

    sigh...don't people search forums anymore?
    http://discussions.apple.com/thread.jspa?messageID=7042093&#7042093

  • What is the best way to lay out color-coded Excel data in InDesign?

    I’ve been away from layout for some time. I now need to lay out color-coded Excel data (3 columns, 200 rows) in InDesign 5.5. The data will need to be in alpha order and each row will be color coded, with a color key at the top of the page. What is the best way to lay this out? Should I use the table tool and create a new style for each color that I need to use?
    Thanks for your help.

    I think this will work in CS3.
    Start off by inserting Styles of WEEK, Mon to Friday (as per left)
    Set the Week No. to Bullets and Numbering and insert as per screen shot
    Do the same for Days Monday through to Sunday
    Also set up Monday style NEXT STYLE to be Tuesday
    When you get to Sunday - loop the Styles back to WEEK style.
    Then as per first screen shot you just have to insert RETURNS all the way down to initiate the style.

  • How is the best way to manage the stats table?

    Hello!
    I have the Integration 2.1 working with an Oracle 8.1.7 db. I noticed that the table
    STATS is growing pretty fast.
    How is the best way to manage this table?... I haven't found something related with
    this issue in the documentation, but at least I want to know how to safely delete
    records from this table.
    For example, if I know the minimal time I have to keep in the table, is quite simple
    to create a shell script and/or Oracle pl/sql job to trim the table.
    I hope somebody can help me!!!!
    Thank you!
    Ulises Sandoval

    Write an app people want to buy and rate highly.

  • Best way to back out data changes after a release

    Hi,
    I'm trying to decide on the best way to backup some production data in case a release fails and we need to roll back the changes. This would be for data updates only, not schema changes. We have extremely limited access to production, and another team handles all the RMAN backups. The people who actually implement our releases are also pretty prone to mistakes.
    I have thought of two options. The tables we want to backup are about 9 MB total in size (it's about 10 codes tables).
    1. Create a bu table for each of the tables before the release. So for JENNSTABLE, we would create a JENNSTABLE_BU using CTAS. If we need to revert, we can drop JENNSTABLE and rename the JENNSTABLE_BU accordingly. The bu table would remain in production until the next release, where it would be reused again. This would be really easy to script and therefore avoid any mistakes by the production support team who implements our instructions. We would also be able to determine what values changed by querying the bu table at any time (currently old values are not retained anywhere).
    2. Use datapump to export the 10 tables, then truncate the tables and import the previously created files to restore the original data. I'm hesitant to use this method because I've never used datapump before, and as we don't have access to the servers, creating file system files makes me a little nervous. If I used a bu table, I can logon to the database and at least tell if it exists.
    Are there any preferred methods for doing this (besides restoring a table w/ RMAN)? Is there a best practice? Any advice is appreciated!
    -Jenn
    Oracle 10g
    UNIX Solaris

    Hi sb92075,
    That's a good suggestion. FLASHBACK_ON is set to no on my database, but if I understand correctly, I can still do a FLASHBACK TABLE and the undo data would be used. Is that correct?
    My concerns w/ using Flashback are ..
    1) The client might decide to rollback the changes a week after they've been executed. The undo data might not be available and the flashback would fail.
    2) If any of the following processes are part of the release, the flashback wouldn't work:
    "The following DDL operations change the structure of a table, so that you cannot subsequently use the TO SCN or TO TIMESTAMP clause to flash the table back to a time preceding the operation: upgrading, moving, or truncating a table; adding a constraint to a table, adding a table to a cluster; modifying or dropping a column; adding, dropping, merging, splitting, coalescing, or truncating a partition or subpartition (with the exception of adding a range partition)."
    Can you address those two issues? Thanks so much for taking the time to respond! This forum has helped me immensely with my work.
    -Jenn

  • What the best way to create User defined table with ADDON purpose

    Hi folks, how are you ?
    I´m beginner in development to business one, and I m studying to develop ISV addons.
    But, during my exercises and analisys, I learned that have two ways to create tables and fields in business one. One way is throght by wizard in business one using Tools Menu > Configuration Tools > User Defined Tables >
    Obs: I ´m using Business One Patch Level 9.
    Other way, is create the tables and fields using DI API
    But, my question is. When I develop one addon, or one UDO form that uses one set of user defined tables or used defined fields that where created by the first way (by wizard in B1), how I deploy this in other business one installation ? The package process will ensure the creation of this tables in another enviroment or I must implement the creation of user defined tables using DI API so that this code is called during the installation?
    If in cases of addon develop I must use DI API to create user defined tables, How can I use my classes with this responsibility in package process ?
    Thanks my friends.

    Hi Renan,
    You just need to put your logic in to the startup of your application, after you've established your connection to the UI API and DI API. All this will be triggered in the constructor of your main class.
    namespace MyNamespace
    public class MyAddon
      bool runAddon = true;
      bool initialised = false;
      const string ADDON_NAME = "My Addon";
      public static void Main()
            MyAddon addOn = new MyAddon();
            if(runAddon)
                  System.Windows.Forms.Application.Run();
            else
             Application.Exit();
      public MyAddon()
            // Connect to SBO session for UI
            if(!SetApplication()) runAddon = false;
      private bool SetApplication()
            // Code goes in here to establish UI API and DI API connections
            // See SDK samples for examples
            // You should also define and filter the UI API events your addon will trap at this stage and create any menus
            // Call your routine to check if the required UDFs/UDTs exist on this company
            initialised = CheckInitialisation();
            if (!initialised)
               //  AddOn not yet intialised on this company so prompt the user to run the intialisation process
              int iResponse = app.MessageBox("The " + ADDON_NAME + " addon will now create all required fields and tables."
                                             + System.Environment.NewLine + System.Environment.NewLine
                                             + "WARNING: It is strongly recommended that all other users are logged out of this company "
                                             + "before running this process. Are you sure you wish to continue?", 2, "Yes", "No", "");
              if (iResponse == 1) initialised = InitialiseAddOn(); // Call your routine to create the objects
            return true;
    Kind Regards,
    Owen

  • Best way to insert in a table througth a database link

    Hi all,
    i have two databases (oracle 10g, windows 2003 server)
    Database A and Database B
    i need to insert data in a table (Table_A) that lives in database A
    The data i have to insert is in a table that lives a database B
    I have a database link from database B to database A
    so, connected to database B, i'm trying the following :
    insert into table_a@database_link_to_A
    select col1
    from table_b
    where col1 is not null
    This query is taking forever, and i have to cancel it.
    I'd like to hear from your experience. Wich is the best way to accomplish this task ?
    Best Regards
    Rui Madaleno
    NOTE: I forgot to mencion that Table_A does not have any trigger or indexes.
    Edited by: ruival on Jan 20, 2010 3:51 PM

    Try this:
    insert /*+ append */ into table_a@database_link_to_A select col1 from table_b where col1 is not nullOr
    Sqlplus COPY another option.
    [http://www.praetoriate.com/oracle_tips_dm_sqlplus_copy.htm]
    HTH
    -Anantha

  • Best way to update an OLTP table ?

    Hi,
    We have an OLTP table with huge data.
    We need to update a status column from 'N' to 'Y' for almost 70% of rows based on some condition.
    This table may be accessed by hundreds of sessions at a time.
    So, what is the best way to do the same.
    Rgds,
    Rup

    if someone is using the table, ddl cannot be done (or at least you would have to wait maybe a long time)
    quick test...
    SQL> create table bank
      2  (id number primary key
      3  ,acc number
      4  ,ind varchar2(1)
      5  )
      6  /
    Table created.
    SQL> insert into bank
      2  select rownum
      3       , rownum * 10
      4       , 'N'
      5    from all_objects
      6   where rownum <= 10
      7  /
    10 rows created.
    SQL> commit;
    Commit complete.
    SQL> update bank
      2     set acc = -10
      3   where id = 10
      4  /
    1 row updated.new session
    SQL> alter table bank
      2  add new_ind varchar2(1)
      3  /
    alter table bank
    ERROR at line 1:
    ORA-00054: resource busy and acquire with NOWAIT specifiedwell, not a long time... but anyway you can't do ddl while someone is working on the table.

  • Best way to clean out Mac

    I am getting a new MacBook Pro this week and I wanted to give my old one to my son. Once I transfer all of my data to the new computer, I would like to clean everything but the programs out of the old Mac before I give it to him. The old one has been a bit buggy of late. What is the best way to do this so that he can start over with a clean slate?

    Hi DKK,
    John gives some great advice, however you'll lose the installed programs. There's a good chance, though that you'll resolve the sluggishness. You can always reinstall the programs afterwards.
    If you do go the route of an Archive & Install (assuming you're reinstall Leopard and not Snow Leopard) while you won't lose the installed programs there's a good chance that they may not work properly and you'll need to reinstall them anyways.

  • Best way to load data in table from combination of Table and flat file?

    Hi All,
    Could you please share your thoughts on best way of achieving this objective -
    Flat File - 15 Million records (Field A,B,C)
    Table A - 15 Million records ( Field A,D)
    Objective -
    Load Field A,B,C,D in Table B from Flat file and Table A.
    Data can be loaded from flat file in Table B then updated from Table A but this update operation is taking lot of time. (Intermediate Commit, Bulk operations already tried)
    Regards,
    Dark Knight

    Environment -
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Tables are analyzed.
    Indexes are their.
    Update statement using the index.
    Data is close to 200 MB.
    I am interested in knowing if there are alternate ways of doing this, other than conventional way of loading data then updating it.

Maybe you are looking for

  • Can I have photos that belong to no event?

    Hi, I love using iPhoto 09 to manage my pictures. I do a lot of buying and selling on craigslist and often take pictures of the items i am selling. When i import my pictures from my phone to iPhoto, it has to create an event for those pictures. Since

  • File Receiver - before message processing *urgent*

    Hello experts, I have a scenario where i  need to execute a script in File receiver adapter. problem: "i send an xml file to target system, but as long as there is a .xml file in the directory, it should not send. He should wait and send only then wh

  • Display all Acct_No's in a subject line of a Form_letter Report.

    Hi Everyone,      I have a problem in the reports. I have created a report which involves a 'Form_Letter' & 'Tabular' Styles. In the Subject line of the form_letter_text there is a field selected from database-table-column that is as below: Sub: Issu

  • Change color on a row in list

    Hi, I want to change color on my lists rows with buttons (look att the picture) i want to be abel to choose more then 1 item and change the color on all that is marked and i want to do this with javascript :)

  • Protect variants in BEx reports - BI 7 version

    Hi, BI 7.0 version of BEx reports do not have the 'Protect variant' option. Is there any other way of Protecting variants from being changed by other users. Any help is highly appreciated. Thanks.