Inventory by LocationId (were locations are hierarchical)

Hi,
I have a problem with an inventory system I'm designing.  It is an inventory system by LocationId.   The problem I have is that the locations are hierarchical.   By hierarchical I mean that a given location might belong to a next location.
For example given the following (simplified) schema of 3 tables (Locations, Articles and Inventory)
CREATE  TABLE Locations (
LocationId                 INTEGER NOT NULL,
ParentLocationId           INTEGER NULL,
CONSTRAINT w_Ub_LLAVE PRIMARY KEY (LocationId)
GO
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (1,NULL);
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (2,NULL);
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (3,NULL);
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (4,1);
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (5,4);
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (6,4);
INSERT INTO Locations (LocationId,ParentLocationId) VALUES (7,5);
CREATE TABLE Articles  (
ItemId                     INTEGER NOT NULL,
Description                VARCHAR(50),
CONSTRAINT ArticlePK PRIMARY KEY (ItemId)
GO
INSERT INTO Articles (ItemId,Description)  VALUES (100,'BREAD');
CREATE TABLE Inventory (
LocationId                 INTEGER NOT NULL,
ItemId                     INTEGER NOT NULL,
Qty                        DECIMAL(14,4) NULL,
CONSTRAINT InventoryPK PRIMARY KEY (LocationId,ItemId)
GO
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (1,100,5);
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (2,100,5);
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (3,100,5);
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (4,100,5);
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (5,100,5);
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (6,100,5);
INSERT INTO Inventory (LocationId,ItemId,Qty) VALUES (7,100,5);
I would like to list the contents by locationId.
For example, if I list LocationId=1 I should get 
5 (in LocationId = 1) + 
5 (in LocationId = 4 which belongs to 1) + 
5 (in LocationId=5 which belongs to 4 which belongs to 1) + 
5 (in LocationId=6 which belongs to 4 which belongs to 1) +
5 (in LocationId=7 which belongs to 5 which belongs to 4 which belongs to 1)
= 25
If I list LocationId=7 I would only get 5 (those in locationId=7)
If I list LocationId=5 I would bet 10 (those in LocationId=5 and those in LocationId=7).
Hopefully I was able to explain myself.   Does anybody know how this could be done?
Thanks,
Edgard

One way to solve this is expanding the hierarchy starting from the node in question all the way down till the last descendant. Then you can join the result to the inventory table to aggregate.
DECLARE @LocationId int =5;
WITH TC AS (
SELECT
LocationId AS ReportsTo,
LocationId
FROM
Locations
WHERE
LocationId = @LocationId
UNION ALL
SELECT
P.ReportsTo,
C.LocationId
FROM
TC AS P
INNER JOIN
Locations AS C
ON C.ParentLocationId = P.LocationId
SELECT
A.ReportsTo,
B.ItemId,
SUM(B.Qty) AS sum_Qty
FROM
TC AS A
INNER JOIN
Inventory AS B
ON A.LocationId = B.LocationId
GROUP BY
A.ReportsTo,
B.ItemId
GO
It gets a little bit more complicated if you want to see all locations, their quantities and the aggregation of the descendants.
WITH TC AS (
SELECT
LocationId AS ReportsTo,
LocationId
FROM
Locations
UNION ALL
SELECT
P.ReportsTo,
C.LocationId
FROM
TC AS P
INNER JOIN
Locations AS C
ON C.ParentLocationId = P.LocationId
, Agg AS (
SELECT
A.ReportsTo,
B.ItemId,
SUM(CASE WHEN A.ReportsTo = B.LocationId THEN B.Qty END) AS Qty,
SUM(B.Qty) AS TotalQty
FROM
TC AS A
INNER JOIN
Inventory AS B
ON A.LocationId = B.LocationId
GROUP BY
A.ReportsTo,
B.ItemId
, LocHie AS (
SELECT
LocationId,
CAST(LocationId AS varbinary(900)) AS SortBy,
0 AS lvl
FROM
Locations
WHERE
ParentLocationId IS NULL
UNION ALL
SELECT
C.LocationId,
CAST(P.SortBy + CAST(ROW_NUMBER() OVER(PARTITION BY P.LocationId ORDER BY C.LocationId) AS binary(8)) AS varbinary(900)),
P.lvl + 1
FROM
LocHie AS P
INNER JOIN
Locations AS C
ON C.ParentLocationId = P.LocationId
SELECT
REPLICATE('|', 8 * lvl) + LTRIM(A.LocationId) AS LocId,
B.ItemID,
B.Qty,
B.TotalQty
FROM
LocHie AS A
LEFT OUTER JOIN
Agg AS B
ON A.LocationId = B.ReportsTo
ORDER BY
A.SortBy;
GO
This approach will not perform well if you have too many levels in the hierarchy and a procedural approach that traverses each level at a time, starting from the leaves, will perform better.
Itzik Ben-Gan has a whole chapter dedicated to Graph theory in his book "Inside Microsoft® SQL Server® 2008: T-SQL Querying".
http://shop.oreilly.com/product/9780735626034.do
AMB
Some guidelines for posting questions...

Similar Messages

  • If the drive my pictures were located on accidently got formatted and are no longer found on my hard drive but are still saved in my organizer on photoshop elements can I still use them?

         My husband accidently formatted the drive my pictures were located on. He tried to go back and restore but they were no where to be found. Now the photos that are located in my organizer on PSE7 say that the file is missing and it won't let me do anything to the picture. Is there any thing I can do that will allow me to use them. I was not able to back my photos up to a disk before this inccident happened because the burning drive wasn't working right. So other than what is located in my organizer I have no other hard copy of my photos. Please response with good news cause there are quite a few pictures in my organizer that I would love to be able to do something with them because they are all I have left of my dog since he passed away a few months ago.

    The only answer I have is not a pleasant one. Your photos are gone. There may be computer services that might be able to retrieve photos from a formatted drive (and they might not be able to retrieve the photos from the formatted drive). These services are usually quite expensive.
    PSE has low res thumbnails. You could blow them up in the Organizer to single image view, and then do a screen capture to save these low-quality photos. You would have to do this one by one.
    In the future, making backups is a very important step. If your burner isn't working, you need to get it fixed, or you need to get an external hard drive for backups. You are one of a large number of people who have written here that your photos are gone ... and for anyone else reading this far, don't let this happen to you.

  • Where are my documents that were located in the Adobe reader on my mobile phone before the update

    I cannot find my documents that were located in Adobe reader before this update creating the cloud. How do I retrieve my documents?

    Could you please let us know if you are using Adobe Acrobat DC on Android or iOS. If you are using iOS, please try the following:
    How to manage files in Adobe Acrobat DC for iOS
    For Android, could you please try these steps: How to open PDFs on Adobe Acrobat DC on Android
    Please let us know if none of the above helps you.
    Thanks,
    Adobe Reader Team

  • How can we get the location from location area code?

    Hi All,
    i have an application which successfully runs on Motorola L6 and it gives me the cell-id, Location area code, and Mobile Network Code, and Mobile Country Code. Now I want to know how can I get the location ( I mean the name of the location) through location area code. And one more thing can we get current MNC and current MCC through j2me because I have written a code for getting this information for sony ericsson cells but dont have a handset to try out. Anyway if anyone has the information then please let me know
    Thanks in advance
    Sunil

    I donot think you have a direct blog..
    check this blog for java proxies ..
    /people/prasad.ulagappan2/blog/2005/06/27/asynchronous-inbound-java-proxy
    AND CONFIGURE A RFC..

  • Functional locations are not transfered to the client

    Hi,
    I have the problem that no functional locations are transfered to the xMAM client.
    I defined a func. loc. selection variant and assigned it to the master data selection of xMAM.
    If I create a new notification using a func. loc. it isn't shown on the client (weather the notification or the func. loc.). If I open the notification on the backend, I receive the message that the notification is already transfered to the client. But where is it???
    Any idea?
    Thank you and regards,
    Florian

    Hi again,
    after some testing, I got it working.
    1. deleted all log messages for my mobile device (MEREP_PURGE).
    2. executed MEREP_EX_REPLIC with MAM30_030
    and then it worked. Now funcional locations are transfered to the client.

  • Live meeting - After click Join the Meeting, it prompted for MeetingID, Entry and Location are blank, need to key in information manually

    Live meeting issue:
    After click Join the Meeting, it prompted for MeetingID, Entry and Location are blank, need to key in information manually
    1. It seems OK on Live meeting client settings.
    2. Then uninstall and reinstall live meeting client and addons. live meeting version now is 8.0.6362.41
    3.can schedule live meeting success.
    but issue persists.

    Live meeting issue:
    After click Join the Meeting, it prompted for MeetingID, Entry and Location are blank, need to key in information manually
    1. It seems OK on Live meeting client settings.
    2. Then uninstall and reinstall live meeting client and addons. live meeting version now is 8.0.6362.41
    3.can schedule live meeting success.
    but issue persists.

  • Got an Error Message using the Featured News Composition Widget regarding the locations are too large to rasterize.  Cannot Preview page.

    I keep getting an Error Message when Previewing a page that has the Feature News Composition Widget.  The Message says that the locations are too large to Rasterize and I need to make it smaller in size.  I tried all of this burt nothing worked.

    Hi Zak,
    Many thanks for your 'correct' and prompt answer.  I tried to make it CORRECT on the Forum, but after clicking the link, did not know where to go since this is my first time using this forum. 
    As it turned out, I was indeed using the font (Georgia) but did not realize that this particular font can also be used as a System font as well.  So I chose the wrong Georgia font which was the System font.  I corrected this issue throughout and made doubly sure that I used the Web Font Georgia.
    Many thanks again for your help and assistance.
    The Shulammite

  • Locations are locked, pls help.

    i went to Privacy->Locations, locations are on and i cant turn it off or turn other apps on/off.
    what do i do?

    Your friend needs to remove the activation lock. You can do nothing about it.
    See:  http://support.apple.com/kb/PH13695
    Your friend has to prepare the iPhone, before he or she is giving it away, see this document:
    What to do before selling or giving away your iPhone, iPad, or iPod touch

  • Help-Task not found - Please check the Task Type, Name and Location are cor

    HI all,
    i have upgraded my owb from version 11gr1 to 11gr2. the installation is complete and all my mappings and objects are imported successfully.
    i was able to execute the mappings using the sql code:
    @/oracle/product/11.2.0/owb/rtp/sql/sqlplus_exec_template.sql
    by logging into sqlplus as the user in whose schema mappings are deployed.
    hOwever, suddenly i am getting the error since sometime back - not sure what might have happened or what might have gone wrong. can someone please help me understand what might be wrong - how to decode this?
    Here is my error:
    @/oracle/product/11.2.0/owb/rtp/sql/sqlplus_exec_template.sql
    Role set.
    Enter value for 1: WSODS
    Call completed.
    Enter value for 2: ODS_SCHEMA
    Enter value for 3: PLSQLMAP
    Enter value for 4: MAPPING_1
    Enter value for 6: ","
    Enter value for 5: ","
    Stage 1: Decoding Parameters
    |  location_name=ODS_SCHEMA
    |  task_type=PLSQLMAP
    |  task_name=MAPPING_1
    Stage 2: Opening Task
    begin
    ERROR at line 1:
    ORA-20001: Task not found - Please check the Task Type, Name and Location are
    correct.
    ORA-06512: at "OWBSYS.WB_RT_API_EXEC", line 759
    ORA-06512: at "OWBSYS.WB_RT_SCRIPT_UTIL", line 910
    ORA-06512: at line 2When i execute this: i get the result as follows:
    SELECT warehouse_object_id, store_id, object_type_id, object_type_name, object_name FROM owb$wb_rt_warehouse_objects
    where object_name = 'MAPPING_1';
    WAREHOUSE_OBJECT_ID     STORE_ID                OBJECT_TYPE_ID          OBJECT_TYPE_NAME                                                 OBJECT_NAME                                                     
    15947                   15325                   769                     PLSQLMap                                                         MAPPING_1                                                       
    1 rows selectedEdited by: Chaitanya on Mar 5, 2012 3:33 AM

    Hi Chaitanya,
    Did you get any resolution for this error? I'm facing the same error while trying to execute OWB mapping through this command.
    Any help would be much appreciated. Thanks.
    Regards,
    Jagari

  • How to create in R/3 functional area hierarchies (0FUNC_AREA_0112_HIER)

    Hi all,
    First of all, thank you for your time, any help would be really appreciated and some points will be asigned to helpful answers.
    Now my little problem...
    We need to have in BW Functional Areas hierarchies.
    To do that I have activated 0FUNC_AREA_0112_HIER from bc. The problem is that there aren´t any functional areas structures defined in R/3 for the moment.
    I've been doing some tests creating structures in R/3, transaction SPRO, "Define finantial statement versions", but when I try to upload them to bw, they don't appear in the hierarchy flow of 0func_area infoobject but in 0gl_account, despite I have filled the flag of "assignment of functional areas is permitted".
    Also in R/3, when I run transaction SE38, program RSA1HCAT, Datasource with hierarchy type=0FUNC_AREA_0112_HIER, an error message is displayed: "No hierarchy catalog in the source system".
    That means they are not func area structures but GL account structures defined in R/3. Nobody in my team knows how to create these kind of structures so that I can load them as 0func_area hierarchies.
    Could you help me please?
    Thank you very much,
    JuliaM

    Hi Julia,
    Got the same issue with trying to create/load the functional area hierarchy.
    Don't know if this helps but if you want to use the hierarchy as defined by the financial statement version, use the hierarchy on the IOBJ 0GLACCEXT - Financial Statement Item.
    Setup as follows:
    IOBJ: 0GLACCEXT
    Hier: 0GLACCEXT_T011_HIER
    Text: 0FUNC_AREA_TEXT and 0GL_ACCOUNT_TEXT
    I'll be monitoring your thread for an answer if your initial issue. If you find a solution elsewhere it would be great if you could post it here. Thanks!
    Best Regards,
    Anders

  • The dates my photos were taken are now incorrect.  Any suggestions on how to get the correct dates back?

    The dates my photos were taken are not incorrect.  Any suggestions on how to get the correct dates back?

    Thank you Winston.  This works and I can adjust several photos at the same time.

  • NOKIA 800 Lumia 'Location Area not Allowed'

    I have noticed that when the phone receives a message that the Location Area is not allowed by a FEMTO Cell (made by HUAWEI) its display says that there is no signal strength at all and that only emergency calls are allowed. Actually the phone is working normally and it can make and/or receive calls or connect to the internet. Other phones do not appear to have this problem. Please check and update firmware. I have tested 3 Lumia 800 and all of them have the same behaviour under the aforementioned circumstances.

    The Lumia 800 does have very robust scratch resistant glass which is fine under most conditions. Saying that, I have heard of 2 instances of scratched displays. The scratches are in the coating and doesn't actually go into the glass itself and only visible when angled to the light. 
    Personally I don't have a screen protector on neither the Lumia nor the N9 at the moment but I have tried a few. Problem is the curved edge and the swiping. Most of them come off at the edges after a while and then dust gets underneath. There was one very cheap one that I got from ebay which worked the best. It was very soft and thin and scratched so easily but still came off after a week and a half so haven't used any since. If you are really worried about scratches, a better bet might be to get a proper full case but you would be hiding what is probably the best looking phone currently on sale. 

  • Locator area displays unauthoritative business transaction types

    Hi,
    I created a service business transaction type (ZXXX). Some users can see the details of this BT in the locator area (nearly all of the fields) although they have no authority for displaying. Indeed when they double click the relaited row for ZXXX, systems warns "There is no authorization for displaying...".
    So i want they are not able to see these documents in the locator area.
    Regards.
    Sadi Yılmaz

    Our system already had business area link to each plant.
    However I don't think the business area value is defaulted from plant as a plant can be link to multiple business areas. Based on a plant, how do system determined which business area to be pulled to MIRO?
    <i>the business ares a is linked to the plant (and not the way back), that means from a plant you have always a unique busines area. This is set up in transaction OMJ7, pls have a look</i>
    We don't turn on the business area balance sheet (OB65). Would you please kindly advise what will be the impact to turn this on?
    <i>quite a lot... In this case don't turn it on, but that also means there won't be automatic derivation (whatever you customized in previous step)</i>
    One last question the enhancement LMR1M001 to derived the business area, from what data will system derive the business area (from vendor master, Purchase order or from where?)
    <i>it just depends on your coding, but basically you have the information in the exit, what you have normally in MIRO.</i>
    <i>Would be good to know, what is your exact requirement, why you want to use business area in case of MIRO postings (and in case of other postings as well).</i>

  • Does my desktop come with wireless capability with no need for a separate router needed to be purchased, when airport is opened up belkin wireless is checked and other locations are listed but locked? Does my xfinity unit have one or just a modem? TIA

    Does my desktop come with wireless capability with no need for a separate router needed to be purchased, when airport is opened up belkin wireless is checked and other locations are listed but locked? Does my xfinity unit have one or just a modem? TIA

    Your iMac does have wireless capability. It does need, however, some wireless network in order to connect to the Internet. It sounds like there are several networks in your area, including one Belkin router that is not encrypted and several other networks that are. I presume that you would know if the Belkin one is yours, and you would have mentioned it. Do not use someone else's network without their permission. In some jurisdictions it is illegal, in others it is merely foolish.
    It is impossible to know what Xfinity has given you. Possibly it is only a cable modem, or perhaps it has a router built in. Call them and ask them. If it has a router built in, get them to help you set it up. Note that some tech support people for Internet service providers will resist working with Macs. Be persistent, it is not that different.
    If they did not provide a router, you will need to get one. Apple makes the AirPort Extreme base station, the AirPort Express base station and the Time Capsule. Other companies have their own. Be sure you get one that is up to date and has 802.11n capabilities (for the highest speed) and go on from there.
    Best of luck.

  • Files that were moved are still displaying in old location.

    Hello,
    I was recently doing some reorganization of some files in my iCloud account in Finder (In the iCloud tab). When I went to sign into iCloud.com the next day and go to iCloud Drive, for some reason the images that I had moved the day before were still in their old locations. The day before, I also rearranged some folders and made some new ones. Those were updated when I went to iCloud.com, but the images were still there. Here are some screen shots showing what my Finder looks like versus iCloud.com, as of right now. (I do realize that there are some extra apps displayed in iCloud.com, but just ignore those. Notice the images, like the first two listed on the screen)
    Notice the extra images on iCloud.com. Anybody know why this is happening? (I tried clearing my cache and cookies, but with no avail)
    Thanks in advance for the help!
    Alan

    Ok,
    I solved it. For some reason when I moved the event folder it created a second event folder in iMovie. This second event folder seemed to be overriding, or not allowing the original event folder to be read. So I moved all of the video files out of the original event folder and moved them to the new event folder.
    It's currently re-generating thumbnails for all the videos but this seems to have solved the problem.

Maybe you are looking for

  • Acct &: Statement & already exists - FF.5

    Hello, I am trying to import an extract using transaction FF.5 to the bank Itau, but this generates the following error "Acct &: Statement & already exists", analyzing realized that this message occurs because the program is trying to contain twice t

  • Long text not appear in E-mail Notification (Smartform)

    Dear Gurus, Need your insight on this issue. I'm trying to insert long text (Response/Description/etc) from the message into body of e-mail notification. I use function module 'CRM_DNO_READ_ORDER_TEXT'  to get the text in the smartform and then use f

  • Instructions on adding a trusted site.

    how do I change my security settings to add a trusted site?

  • CDC Toolkit

    Hi all, I am trying to compile code I wrote for the J2SE in the CDC toolkit expecting some obvious errors for certain libraries that do not exist. Instead I am getting errors that it does not find the standard libraries. I set up the classpath to the

  • Does WL70 Web Service Support Sessions?

    Does anybody know how to make WL70 Web Service support sessions? The "javax.xml.rpc.session.maintain" property on Stub does not seem to work. Without session support, it is almost no use for us because we have to authenticate the user each time. Than