Running Total in Qlikview - qlikview

My table has the stock movement for each item by day. So at any point if I want to find the current stock, I need to sum all the stock movements from the day business started.
Now I want to create a report which shows the stock level over a period of time. The period can be selected by the user.
Here is a simplified version of my table:
Stock:
LOAD * INLINE
[Brand,Item,Reason,Date,StockMovement
EveLom,E001,OpeningStock,01/01/2014,200
EveLom,E001,Sale,05/01/2014,-100
EveLom,E001,Purchase,01/03/2014,100
EveLom,E001,Sale,01/05/2014,-50
EveLom,E001,Sale,01/10/2014,-50
EveLom,E001,Sale,21/10/2014,-20
EveLom,E001,Sale,01/01/2015,-30
EveLom,E001,Sale,01/03/2015,-10
EveLom,E001,Purchase,01/04/2014,100
EveLom,E002,OpeningStock,01/01/2014,2000
EveLom,E002,Sale,05/01/2014,-100
EveLom,E002,Purchase,01/03/2014,100
EveLom,E002,Sale,01/05/2014,-50
EveLom,E002,Sale,01/10/2014,-50
EveLom,E002,Sale,01/11/2014,-20
EveLom,E002,Sale,01/01/2015,-30
EveLom,E002,Sale,01/02/2015,-10
EveLom,E002,Purchase,01/03/2014,100
LQ,L001,OpeningStock,01/01/2014,1000
LQ,L001,Sale,05/01/2014,-100
LQ,L001,Purchase,01/03/2014,100
LQ,L001,Sale,01/05/2014,-50
LQ,L001,Sale,01/10/2014,-50
LQ,L001,Sale,21/10/2014,-20
LQ,L001,Sale,01/01/2015,-30
LQ,L001,Sale,01/03/2015,-10
LQ,L001,Purchase,01/04/2014,100
LQ,L002,OpeningStock,01/01/2014,5000
LQ,L002,Sale,05/01/2014,-100
LQ,L002,Purchase,01/03/2014,100
LQ,L002,Sale,01/05/2014,-500
LQ,L002,Sale,01/10/2014,-500
LQ,L002,Sale,01/11/2014,-200
LQ,L002,Sale,01/01/2015,-300
LQ,L002,Sale,01/02/2015,-100
LQ,L002,Purchase,01/03/2014,100
];
There are four items and they are grouped under 2 brands.
Now I want a stacked bar chart for Stock Level by Brand Vs Month.
The chart should look like below.
Months will be in X-Axis.
Stock will be in Y-Axis.
I tried several methods without any success. Any ideas/guidance will be much appreciated.
See qlik community thread here.

Pulled from the Qlik community
Expression:
if(YearMonth=Min(TOTAL YearMonth),
sum(TOTAL <Brand> {<YearMonth={"<=$(=Min(YearMonth))"}, Year, Month>} StockMovement),
sum(StockMovement))

Related

Merge row cells after Summing up multiple rows by grouping in ssrs

I have a matrix report in SSRS which is grouped by Product Class, Tax Type and Depot Name as shown in the following image.
What I am trying to achieve is to get the sum of both the Order Volume and Marker Volume based on the tax type grouping and populate them respectively in the order volume total and marker volume total fields.
So I put the following queries for them respectively:
=Sum(Fields!OrderVolume.Value, "TaxType")
=Sum(Fields!MarkerVolume.Value, "TaxType")
I then got the total as expected but it's splitting. How can I merge both of them (order volume total and marker volume total) based on the Tax Type?
Kindly help,
Best Regards

Subtotal by unique store with multiple sales staff over period

I am trying to gather various KPI's for salespersons in multiple stores. The goal is to break down store performance into salesperson level.
I am facing an issue when trying to add a hitrate, as this is normally only by store. Number of quotes given / Visitors.
Even though it may not be 100% accurate I still wish to have the KPI by sales person. I am able to do this on a sales person level, but my subtotal for the store is incorrect, as it makes a summation of visitors by sales persons.
Monthly period is to be considered to as sales persons comes and goes throughout the period. Example of what I wish for a Subtotal for the measure "Vis". Store X 370 for month 1,2 & 3. For Store Y 395.
Vis measure = Visitor (Calculation i have tried but gives the wrong result for the store total for the period.)
I have tried various Calculate, Sum, max functions, but nothing seems to provide the result I need.
I hope that someone might be able to help me get along with this.
Example data tables is link as shown below:
enter image description here
Thanks in advance.
This sounds like a case where the HASONVALUE function would be useful.
The idea being that you would the result of that function in an if to determine if you are calculating at your sales person level or a the store level which should contain multiple salespersons. Thus you would have two different calculations, one for the sales person and store combination, and one for the Store level.
Example would be sometime like the following, in this example I am assuming you have a sales person table:
Measure:= IF( HASONEVALUE( Salesperson[Sales Person] ),
[Vis],
[Measure for subtotal]
)
[Measure for Subtotal] would just being the calculation that you want for your store total.
Of course if you filter to just a single sales person, then the totals for the store will just match that sales person.

DAX % of total count if measure qualifies criteria

DAX 2013 standalone power pivot.
I have a sales table with Product and Brand columns, and Sales measure which explicitly sums up sales column.
Task in hand: I need to create 1 measure RANK which would ...
if Product is filtered expressly, then return count of Products that have higher or equal sales amount, divided by total count of products.
If it's a subtotal brand level, show the same but for brands.
My current approach is using RANK and then MAXX of rank which seems working but a no-go - slow nightmare. Excel runs out of memory.
Research: it's been a week. This is the most relevant post i found anywhere, this question here , but it's in MDX.
In my example picture, I'm showing Excel formulas with which I can get to the result. Ideally there shouldn't be any helpers, 1 formula for all.
I.E.
RANK:=IF( HASONEFILTER(PRODUCTS[PRODUCT], HELPER_PROD, HELPER_BRAND)
where HELPER_PROD part would be something like this - need to find a way to refer to "current" result in pivot table like Excel does using [#[...:
HELPER_PROD:=COUNTX(ALL(PRODUCTS), [SALES]>=[#[SALES]]) / COUNTX(ALL(PRODUCTS))
HELPER_BRAND:=COUNTX(
DISTINCT(ALL(PRODUCTS[BRAND])),
[SALES]>=[#[SALES]]) /
COUNT(DISTINCT(ALL(PRODUCTS[BRAND]))
You can use the "Earlier" function to compare with the current record.
ProductsWithHigherSales:=CALCULATE(countrows(sales),
FILTER(all(Sales),
countrows(filter(Sales,Sales[Sales]<=EARLIER(Sales[Sales])))
))
Using Earlier function in measures: can-earlier-be-used-in-dax-measures
Used workbook: Excel File

Excel PowerPivot Help: Totals is not summing the Absolute Value correctly

I know PowerPivot is not programming, but I wanted to see if I could get help or a recommendation on how to get the total rows to correctly calculate the sum of Absolute Values at a higher aggregation level that the detailed data in a PowerPivot data model.
Here is my example: This is detailed data format. There are 2 hierarchies:
1. Product Group\Product Family\**Material** '3 columns'
2. Region\**Plant**\SalesMgr\Employee\Customer '5 columns'
Hierarchy represents 8 columns in my data model
All data in the data model is at the lowest level (i.e. Material/Customer). However I want to calculate Forecast Accuracy at Material/Plant Level (a higher aggregation level).
DataModel Column9: Sales 'Sales at the detailed Material/Customer'
DataModel Column10: Forecast 'Forecast at the detailed Material/Customer'
Calculated Column11: AbsoluteError = ABS(Forecast - Sales) 'calced at Mat/Cust'
PowerPivot DAX formulas/measures, shortened for simplicity
TotalSales:=SUM(Sales)
TotalAbsError:=SUM(AbsoluteError)
MAPE:= TotalAbsError/TotalSales
ForecastAccuracy:= 1 - MAPE (Mean Absolute Percentage Error)
This calculates the data correctly at the Material/Plant level when I create my Pivot Table. However the Total values in the Pivot Table are incorrect.
For example, the Total of AbsError is the Sum of 20 rows of Material/Customer Combinations. I need the Total of only the 5 Material/Plant Combinations. The 20 rows of detailed Material/Customer data aggregates up to only 5 rows of Material/Plant Combinations.
I have a sample spreadsheet I can share. Thanks Dimitry for updating the question!
I would like to post the spreadsheet / powerpivot so that the StackOverflow community can see it. I assume I have to post a link. I will start trying to figure out how.
Thanks
David

Access 2013 SQL to perform linear interpolation where necessary

I have a database in which there are 13 different products, sold in 6 different countries.
Prices increase once a year.
Prices need to be calculated using a linear interpolation method.  I have 21 different price and quantity increments for each product for each country for each year.
The user needs to be able to see how much an order would cost for any given value (as you would expect).
What the database needs to do (in English!) is to:
If there is a matching quantity from TblOrderDetail in the TblPrices,
use the price for the current product, country and year
if there isn't a matching quantity but the quantity required is greater than 1000 for one product (GT) and greater than 100 for every other product:
Find the highest quantity for the product, country and year (so, 1000 or 100, depending on the product), and calculate a pro-rated price.  eg.  If someone wanted 1500 of product GT for the UK for 2015, we'd look at the price for 1000 GT in the UK for 2015 and multiply it by 1.5.  If 1800 were required, we'd multiply it by 1.8.  I haven't been able to get this working yet as I'm looking at it alongside the formula for the next possibility...
If there isn't a matching quantity and the quantity required is less than 1000 for the product GT but 100 for the other products (this is the norm)...
Find the quantity and price for the increment directly below the quantity required by the user for the required product, country and year (let's call these quantitybelow and pricebelow)
Find the quantity and price for the increment directly above the quantity required by the user for the required product, country and year (let's call these quantityabove and priceabove)
Calculate the price for the required number of products for an account holder in a particular country for a given year using this formula.
ActualPrice: PriceBelow + ((PriceAbove - PriceBelow) * (The quantity required in the order detail - QuantityBelow) / (QuantityAbove - QuantityBelow))
I have spent days on this and have sought advice about this before but I am still getting very stuck.
The tables I've been working with to try and make this work are as follows:
TblAccount (primary key is AccountID, it also has a Country field which joins to the TblCountry.Code (primary key)
TblOrders (primary key is Order ID) which joins to TblAccount via the AccountID field; TblOrderDetail via the OrderID.  This table also holds the OrderDate and Recipient ID which links to a person in TblContact - I don't need that here but will need it later to generate an invoice 
TblOrderDetail (primary key is DetailID) which joins to TblOrders via OrderID field; TblProducts via ProductID field, and holds the Quantity required as well as the product
TblProducts (primary key is ProductCode) which as well as joining to TblOrderDetail, also joins to TblPrice via the Product field
TblPrices links to the TblProducts (as you have just read).  I've also created an Alias for the TblCountry (CountryAliasForProductCode) so I can link it to the TblPrices to show the country link. I'm not sure if I needed to do this - it doesn't work if I do or I don't do it, so I seek guidance again here.
This is the code I've been trying to use (and failing) to get my price and quantity steps above and I hope to replicate it, making a couple of tweaks to get the steps below:
SELECT MIN(TblPrices.stepquantity) AS QuantityAbove, MIN(TblPrices.StepPrice) AS PriceAbove, TblOrders.OrderID, TblOrders.OldOrderID, TblOrders.AccountID, TblOrders.OrderDate, TblOrders.RecipientID, TblOrders.OrderStatus, TblOrderDetail.DetailID, TblOrderDetail.Product, TblOrderDetail.Quantity
FROM (TblCountry INNER JOIN ((TblAccount INNER JOIN TblOrders ON TblAccount.AccountID = TblOrders.AccountID) INNER JOIN (TblOrderDetail INNER JOIN TblProducts ON TblOrderDetail.Product = TblProducts.ProductCode) ON TblOrders.OrderID = TblOrderDetail.OrderID) ON TblCountry.Code = TblAccount.Country) INNER JOIN (TblCountry AS CountryAliasForProduct INNER JOIN TblPrices ON CountryAliasForProduct.Code = TblPrices.CountryCode) ON TblProducts.ProductCode = TblPrices.Product
WHERE (StepQuantity >= TblOrderDetails.Quantity)
AND (TblPrices.CountryCode = TblAccount.Country)
AND (TblOrderDetail.Product = TblPrices.Product)
AND (DATEPART('yyyy', TblPrices.DateEffective) = DATEPART('yyyy', TblOrders.OrderDate));
I've also tried...
I've even tried going back to basics and trying again to generate the steps below in 1 query, then try the steps above in another and finally, create the final calculation in another query.
This is what I have been trying to get my prices and quantities below:
SELECT Max(StepQuantity) AS quantity_below, Max(StepPrice) AS price_below, TblOrderDetails.Quantity, TblAccounts.Country
FROM 
(TblProducts INNER JOIN TblPrices ON TblProducts.ProductCode = TblPrices.Product)
(TblOrderDetail INNER JOIN TblProducts ON TblOrderDetail.Product = TblProducts.ProductCode)
(TblOrders INNER JOIN TblOrderDetail ON TblOrders.OrderID = TblOrderDetail.OrderID)
(TblAccount INNER JOIN TblOrders ON TblAccount.AccountID = TblOrders.AccountID),
WHERE (((TblPrices.StepQuantity)<=(TblOrderDetail.Quantity)) AND ((TblPrices.CountryCode)=([TblAccounts].[country])) AND ((TblPrices.Product)=([TblOrderDetail].[product])) AND ((DatePart('yyyy',[TblPrices].[DateApplicable]))=(DatePart('yyyy',[TblOrders].[OrderDate]))));
You may be able to see glaring errors in this but I'm afraid I can't.  I've tried re-jigging it and I'm getting nowhere.
I need to be able to tie the information in to the OrderDetail records as the price generated will need to be added to a financial transactions table as a debit amount and will show as an amount owing on statements.
I'm really not very good at SQL.  I've read and worked though several self-study books and I have asked part of this question before; but I really am struggling with it.  If anyone has any ideas on how to proceed, or even where I've gone wrong with my code, I'd be delighted, even if you tell me I shouldn't be using SQL. For the record, I originally posted this question on a different forum under Visual Basic. Responses from that forum brought me to SQL - however, anything that works would be good!
I've even tried, using Excel, concatenating the Year&Product&Country&Quantity to get a unique product code, interpolating the prices for every quantity between 1 and 1000 for each product, country and year and bringing them into a TblProductsAndPrices table. In Access, I created a query to concatenate the Year(of order date from tblOrders)&Product(of tblorderdetails)&Country(of tblAccount) in order to get the required product code for the order. Another query would find a price for me. However, any product code that doesn't appear on the list (such as where a quantity isn't listed in the tblProductsAndPrices as it is larger than the highest price increment) doesn't have a price.
If there was a workable solution to what I've just described that would generate a price for everything, then I'd be so pleased.
I'd really like to be able to generate an order for any quantity of any product for any account based in any country on any date and retrieve a price which will be used to "debit" a financial account in the database, who in a transaction history for an account and appear on statements. I'd also like to be able to do an ad-hoc price check on the spot.
Thank you very much for taking the time to read this.  I really appreciate it. If you could offer any help or words of encouragement, I'd be very grateful.
Many thanks
Karen
Maybe no one thinks on an easy solution to the problem, since not all minds work in database thinking.
Easy solution: Create one view that gives all calculated values, not only the final one you need, each one as a column. Then you can use such view in a relation view and use on some rows one of the values and on other rows other values, etc.
How to think is simple, think in reverse order, instead of thinking "if that then I need to calculate such else I need this other", think as "I need "such" and I need "this other", both are columns of an intermediate view, then think on top level "if" that would be another view, such view will select the correct value ignoring the rest.
Never ever try to solve all in one step, that can be a really big headache.
Pros: You can isolate calculated values (needed or not), sql is much more easy to write and maintain.
Cons: Resources use is bigger than minimal, but most of times that extra calculated values does not represent a really big impact.
In terms of tutorial out there: Instead of a Top-Down method, use a Down-Top method.
Sometimes it is better (with your example) to calculate all three values (you write sentences on bold) ignoring the if part, and have all three possible values for your order and after that discard the ones not wanted, than trying to only calculate one.
Trying to calculate only one is thinking as a procedural programming, when working with databases most times one must get rid of such thinking and think as reverse, first do the most internal part of such procedural programming to have all data collected, then do the external selection of the procedural programing.
Note: If one of the values can not be calculated, just generate a Null.
I know it is hard to think on First in, last out (Down-Top) model, but it is great for things as the one you want.
Step1 (on specific view, or a join from one view per calculation):
Calculate column 1 as price for the current product, country and
year
Calculate column 2 as calculate a pro-rated price as if 1000
Calculate column 3 as calculate a pro-rated price as if 100
Calculate column 4 as etc
Calculate column N as etc
Step 2 (Another view, the one you want):
Calculate the if part, so you can choose adequate column from previous view (you can use immediately if or a calculated auxiliary field).
Hope you can follow theese way of thinking, I have solved a lot of things like that one (and more complex) thinking in that way, but it is not easy to think as that, needs an extra effort.