Analysis :: SSAS Calculation With Division Combined With A Time Calculation?

Sep 17, 2015

I have created calcalated measures in a SQL Server 2012 SSAS multi dimensional model by creating empty measures in the cube and use scope statements to fill the calculation.

(so I can use measure security on calculations

as explained here  )

SCOPE [Measures].[C];

THIS = IIF([B]=0,0,[Measures].[A]/[Measures].[B]);

View 2 Replies


ADVERTISEMENT

Analysis :: SSAS Tabular - Preview Of Calculation Not Working

Oct 30, 2015

Does any1 know why preview of a DAX calculation does not work? I mean once you enter the calculation in the bottom of the table it doesnt´t show up.

View 8 Replies View Related

SSAS Time Calculation In Report Builder

Mar 6, 2007

Has anyone been able to get time calculations to show up in Report Builder? I'm using the BI Wizard standard calculations for YTD & Period over period growth, but I can't figure out how to use them within Report Builder. They are available in Report Designer, however. I did find the info about assigning the calculations to a measure group. I tried that, but it didn't have any affect.

Any help is appreciated.

View 7 Replies View Related

YTD Calculation When Using SSAS As Data Source

Jun 14, 2007

I have a cube that tracks sales by sales rep. In this cube, I have dimensions for SalesRep, Product, and Region hierarchies. I also have a Time dimension that provides Fiscal Year, Fiscal Quarter, Fiscal Month, and Calendar Date; the Time dimension also has an attribute showing the first day of the year for any given date (our fiscal year starts on a different date every year).



I have a report that passes StartDate and EndDate parameters back to the cube, and provides sales numbers by Rep, Product, and Region for that given date range. What I would also like is a field that provides YTD sales through the EndDate parameter.



This is a piece of cake for me to implement against the SQL tables, but I am pulling my hair out trying to determine the best way to implement with a cube. Does anyone have any suggestions?



TIA



- Steve

View 1 Replies View Related

Converting Oracle Calculation To Sql Server 2005 Calculation

Jul 19, 2007

Hi I am having to convert some oracle reports to Reporting Services. Where I am having difficulty is with the

calculations.

Oracle

TO_DATE(TO_CHAR(Visit Date+Visit Time/24/60/60,'DD-Mon-YYYY HH24:MISS'),'DD-Mon-YYYY HH24:MISS')



this is a sfar as I have got with the sql version

SQLSERVER2005

= DateAdd("s",Fields!VISIT_DATE.Value,Fields!VISIT_TIME.Value246060 )



visit_date is date datatype visit_time is number datatype. have removed : from MI(here)SS as was showing as smiley.



using:

VS 2005 BI Tools

SQLServer 2005



View 5 Replies View Related

SQL Server 2008 :: Subquery In SSAS Named Calculation

May 8, 2015

I am trying to get a date diff in a named calculation using inner join I am getting

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. #

I have checked online and have been able to get some of my codes right by using the where condition in place of the inner join, but I have not been able to work around the datediff one

(select
DATEDIFF(day,TDate,[DID])
FROM [dv].[dbo].[Dail] as D
inner join
[dv].[dbo].[ANT] as A
on
a.AID = d.AID)

View 0 Replies View Related

Analysis :: Median Calculation Using MDX

May 28, 2015

 I have a fact table fct_line_details having two columns mtid, productivity

  mtid     productivity
  1           400
1           200
1          600
2          700
3         900

I want to calculate the median for each mtid in SSAS . (median for mtid 1=400 )

View 2 Replies View Related

Analysis :: Calculation On Row Level / If Value Is Above Or Less Than Average

Aug 3, 2015

I have a set of data and calculated already the average of a specific measure, incl. the Standarddeviation of this measure. Now I want to create a average measure of the values on row level which arehigher than [Avg]-[StdDev] AND lower of [Avg]+[StDev].As far as I understand I have to check on Rowlevel, which means on Date and Brand Level, if the value of the measure is above or lower than the Mean +/- StdDev.

SUM( FILTER( {[Dim 1].[Attribue].&[selected]},[Measures].[Fact Survey Count] > [Measures].[Mean + 0,5 StDev] AND [Measures].[Fact Survey Count] < [Measures].[Mean - 0,5 StDev] ),[Measures].[Fact Survey Count])

which leads to a wrong result. This one counts all rows if true.With Descendants I got a #Value-Error, probably because I did not understand how the calculations work. I planned to include this in a IIF calculation.

SUM( Descendants(
    {[Dim 1].[Attribute].&[selected],
    [Dim Date].[Date].[Date].CURRENTMEMBER}, Leaves), [Measures].[Fact Survey Count])

View 4 Replies View Related

Analysis :: Calculation Based On Dimension Value

Oct 8, 2015

Need to resolve this calculation, which I would believe is something very common on SSAS environments. 

Like many companies, my company has different ways of calculating Sales and the two I want to focus are Sales Gross and Sales Net. 

At a high level, we calculate Sales Gross as Sales with returns, and Sales Net as Sales without returns.

We have an attribute called Order Type that has various types of orders a user can execute with my company. One of them is Returns. If you return something back to us, we record that as a return line on the sales table. With that, we can calculate that return, breaking data down by Order Type, such as:

Order Type Line Total

Mail Orders $ 776,655.44

Internet Orders $ 2,211,334.00

Call Center Orders $ 11,223,344.00

Credit Orders  $ (55,666.00)

Today, to calculate Sales Gross and Sales Net, we are creating two dimensions: DimSalesGross and DimSalesNet. 

To calculate Sales Gross, we leave the data at the natural state, not making any changes to mappings. 

To calculate Sales Net, we map Credit Orders to Call Center Orders at the ETL level, getting a Net value for sales (Orders - Returns), however, I doubt this is the correct way of doing. 

I would like to have a Line Total Net / Line Total Gross calculation, which would be based on the Order Type value.

Perhaps using a CASE statement in MDX? Is the above possible?

View 4 Replies View Related

Analysis :: Calculation That Excludes Filters

Jul 8, 2015

I'm trying to calculate the average number of sick days per person so that it can be broken down by person role or department or some other dimension. I have a calculation for sick days that works ok and is [measures].[sick days.I'm trying to create another calculation that is [total staff] but it doesn't work.

My final calculation will be [avg sick days] =  [measures].[sick days] / [measures].[total staff]

The bit I can't get to work is making it ignore any filters. For example I have a measure called [staff] and as you would expect it can be broken down by [person].[role] or [department].[department].

I'm trying to get [total staff] to return the total when it's used with [person] or [department]. I've managed to get it to work with [person] by using ROOT([Person]) but then I will need to do this for all different hierarchies that will use it.

View 12 Replies View Related

Mdx/analysis/reporting Service For Date Calculation

Apr 8, 2008

Hi,

I have a cube with the following
DimStartDate
DimEndDate
DimArea
FactDataCount

I need to output the following report

Area 5days 10days 30days
Miami 4 2 1
Memphis 3 3 2

1)Where do I do the dateDiff calculation, at report or cube level?
2)How do I work out which dates belong to the above groups? I'm assuming i have to check if the dateDiff lies between those numbers?

thanks

View 2 Replies View Related

Analysis :: Display Calculation For Structure And Attributes Only

Jun 29, 2015

I have a calculation that granularity is on a specific level and therefore would like the calculation to be only visible/calculate when with a specific dimension structure & attributes

SCOPE([Measures].[Complaint Rate]);
SCOPE([Item Dimension].[Item Structure].Members);
this=(IIF([Measures].[Sales Units]=0,NULL,(([Measures].[Count]/[Measures].[Sales Units])*1000000)));
END SCOPE;
END SCOPE;

This displays the calculation all the time even if no item attributes are selected, I only want the calculation applicable to the structure & attributes belonging to structure - I tried children, currentmember etc. but no luck - its probably something small I am missing. Tried this too

this=(IIF([Measures].[Sales Units]=0,NULL,(([Item Dimension].[Item Structure].CURRENTMEMBER,[Measures].[Count]/[Item Dimension].[Item Structure].CURRENTMEMBER,[Measures].[Sales Units])*1000000)));

View 4 Replies View Related

Analysis :: Total Calculation With Filter For Parallel Period

Nov 30, 2015

I have developed a cube in my work place for analyzing current year sales with previous year sales in Time Hierarchy (Year- Quarter- Month) using Parallel period. If we want to see data for particular Quarters i.e. Q1 and Q2 then total at the year level should also get change. Currently if we only choose 2 quarters in the filter then current year data gets change, however data using parallel period is not getting change accordingly and its shows Total of full year.

View 4 Replies View Related

Analysis :: YTD Calculation For Multiple Hierarchies With SCOPE Statement

Jul 2, 2015

I am stuck in a situation where I want to use YTD for three different calendars of our company and don't want to create three different YTD calculations. However I want to make this work for any measure not for a particular measure

If I create one YTD and try to use in context of three calendars in SCOPE statements then it does not give my right results. Following is my syntax but It does not work.

SCOPE([Billing Date].[SalesCalendar].MEMBERS);
( [Aggregate].[AGGREGATE CODE].[YTD] )   
          = Aggregate({[Aggregate].[AGGREGATE CODE].DefaultMember}*{PERIODSTODATE([Billing Date].[SalesCalendar].[Sales Calendar Year],[Billing Date].[SalesCalendar].CURRENTMEMBER) } );

[Code] ....

However if I comment on one of SCOPE statement , other one works but both don't work simultaneously in context of different calendars.

View 2 Replies View Related

Analysis :: Total Calculation Incorrect When Using IF In Calculated Member

Oct 27, 2015

I cannot understand why Total of calculated member is displayed incorrect. How should I change calculated member for it to work correctly?

Calculated Member:
     CREATE MEMBER CURRENTCUBE.[Measures].AverageScore
        AS IIF([Measures].[Distance]<2001,0,[Measures].[avgscore]/[Measures].[Date Count]),
     VISIBLE = 1;

It seems that Total is calculated without checking value in "AverageScore" for that month.

View 3 Replies View Related

Time Calculation

Mar 26, 2008

i am trying to calculate the time that is spend by user on the internet per site. the file that we receive from the WebProxLog contains the following fields ClientIP, ClientUname,logdate,logTime, ProcessingTime, DestinationHost,DestinationIP. I want to check per user per site how much time the user spend per date. Now my challenge is that if the user connects to the side today and logout and reconnects again to the same side how do i calculate the time spend on the site because the file does not show the logout time

View 3 Replies View Related

Analysis :: MDX To Filter For Completed Periods Only (part Of Annualized Calculation)

Sep 9, 2015

I have been following the tutorial/blog post HERE to create an annualization (or "run rate") of my Gross Amount measure.  What I want to do now is exclude any period that is not "complete".  

For example, if today is 9/9 then Q3 is not complete - only Q1 and Q2 are complete.  And if I'm looking at it monthly then January through August are complete, but September is not.

Cells B5 and D5 look exactly as I expect and want them to be. On row 6 below under each "Gross Annualized" value I have basically just put the formula for what it's actually doing.

What I would like to see in the blue cell is $67,211,697,268 - essentially the most recent annualization for a completed period. The annualization for Q3 is misleading because the quarter has not yet completed.  There's $16b in Q1 and $17b in Q2, so the measly $78m in Q3 (yellow cell) is dragging the annualization down significantly. Even worse, the Gross Amount for Q4 is being treated as a $0.00, which is further dragging down the "2015 Gross Annualized" amount in blue. In a T-SQL average calculation, for example, I think the green cell would be treated as NULL rather than $0.  That's kind of the behavior I want.

So I would like to do two things:

Create a calculation (probably just a 0 or 1 flag) that indicates whether the current period is complete or not.  Again, using 9/9/2015 as an example, Q2 would be complete but Q3 would not be. And August would be complete, but September would not. Make the blue cell show $67,211,697,268 - an annualization based on completed quarters only.

For whatever it's worth here is the current calculation for Gross Annualized.

CREATE MEMBER CURRENTCUBE.[Measures].[Gross YTD]
AS AGGREGATE(
YTD([Pay Date].[Calendar].CurrentMember)
,[Measures].[Gross Amount]),
FORMAT_STRING = "Currency",
VISIBLE = 0;

[Code] .....

View 2 Replies View Related

Help: Date/time In Between And Calculation

Aug 23, 2005

I have a problem with date/time:

1. I have data something like this:
start 07.30
end 16.00
How can i count how many hours and minutes from start to end?

2. Another data
start: 20050805 -> August 5, 2005
end: 20050810
How can I return value that when i insert 20050809 it is between start and end, and if 20050811 it will say false that the date is between start and end

thx

View 1 Replies View Related

Time Calculation With Two Schedule

Feb 12, 2014

I have two table one with employee time in out. Employee is having two shift

[EMPID][Date] [Time]
818401/01/201410:04
818401/01/201411:48
818401/01/201416:17
818401/01/201422:20

Second table shows Schedule for employee

[EmpID][IN1] [OUT1] [IN2] [OUT2]
818510:00:0020:00:0015:00:0020:00:00

How do i get the detail in this format

EmpID Date In1 out1 In2 out2

8185 01/01/2014 10:04 11:48 16:17 22:20

View 6 Replies View Related

Time Calculation Between Two Records With Same IP

Aug 30, 2007

Hello All,

I have some difficulties with TSQL where i need to calculate time between two records in seconds.
Records look like this:
ID IP DATE CHANNEL_ID #CALCTIME
1 10.132.184.226 12/06/2007 08:00:00 406 35
2 10.96.121.230 12/06/2007 08:00:10 1 45
3 10.128.242.214 12/06/2007 08:00:20 4 39
4 10.132.184.226 12/06/2007 08:00:30 2
5 10.96.121.230 12/06/2007 08:00:55 3
6 10.96.121.214 12/06/2007 08:00:59 3 21
7 10.96.121.214 12/06/2007 08:01:20 4
.........................................................................................................

Basically i would need to calculate the time between 2 records with the same IP (next one with the same IP) and calculate the time between the DATE which is basically attached to the first record. As you can see the first #CALCTIME is done between the ID #1 and ID#4 which means that the time difference must be done between the current and the next record.

Really appreciate your help!


Thank you!

Sebastijan

View 1 Replies View Related

Analysis :: Average Calculation On Leaf And Aggregate Parent Level And Above Using Averaged Value?

Sep 14, 2015

At the 2nd level, the calculated measure will only be correct if it is Averaged. And at the 1st level, the calculated measure will only be correct to take these Average value from 2nd level and Sum then up together. 

Level 1 Level 2
A    
X1
X2
=================
(Avg of X1 + X2)  
B
Y1
Y2
Y3
=================
(Avg of Y1 + Y2 + Y3)
===================================================
(Sum of (Avg of X1 + X2)  + (Avg of Y1 + Y2 + Y3) )

Currently, Instead of summing all the 3 averaged value, it is averaging against all the items like,

(Avg of X1 + X2 + Y1 + Y2 + Y3)

My MDX currently looks something like that 

[Measure].[Value] / [Dimension].[Attribute.count] -> so i can get the avarage at the 2nd level but it doesn't require on the 1st level but retaining this value.

How can i do an average on the leaf level and using these average values to sum at parent level?

View 4 Replies View Related

Query Question Time Calculation

Oct 6, 2004

Hi,

I get a no. of seconds (like '33450', varchar) for each day and I have a day field (like '19.10.2004', varchar).

How can I easily convert it into a datetime-field (like 2004-10-19 09:17:50) ?

Does anybody has an idea ?

:confused:

View 5 Replies View Related

T-SQL (SS2K8) :: Time Calculation From Datetime

Oct 29, 2014

I am trying to produce a report that will show a duration in minutes of a time when a room was occupied for a category. Whilst I have the start and end dates and times, the end user must be able to specify not only a range of dates, but a start and endtime of hours in the day in which they are interested in (it will be applied to all days in the range - they are not allowed to specify a different start/endtime per day).

The example I have is a date range of 6 to 17 October, but they only want the times from 09:00 to 21:00, so if a room was occupied from 08:00 to 11:00 they would only want to know the duration as 120 minutes (09:00 to 11:00) not 180.

The data is supplied by a third party, and duration in minutes is supplied, but it is not much use when they are not interested in the 'real' duration.

CREATE TABLE [dbo].[Evts](
[Location_name] [nvarchar](200) NULL,
[Event_Category] [nvarchar](500) NULL,
[Start_Time] [datetime] NULL,
[End_Time] [datetime] NULL,
[Duration] [int] NULL

[Code] ....

---but the expected output is

Location_nameEvent_Categoryduration
RS8CM240
RS8OD480 -- eliminating 08:00 - 09:00 on 17th
RS8OOT300 -- eliminating 08:00 - 09:00 on 13th
RS8SCC150
RS8SODT1740
RS8 SODT180
RS8SODTB60
RS8SODTNT180
RS8TR60

Looking for info regarding to the minute calculation when the start time specified by the user differs from that of the actual startime?

View 2 Replies View Related

Time Duration Calculation Ignoring Overlaps

Apr 16, 2008

Would like to know if it is possible to calculate the duration of a Datetime Start and End Dates ignoring all overlapps?
Eg:
1) StartTime 10:00:00 EndTime 11:00:00 Duration: 01:00:00
2) StartTime 10:30:00 EndTime 11:15:00 Duration: 00:45:00
Total Duration should be 01:15:00 and not 01:45:00

View 16 Replies View Related

Analysis :: Calculation Of average Using DAX AVERAGE And AVERAGEX

Jun 21, 2015

Calculation of an average using DAX' AVERAGE and AVERAGEX.This is the manual calculation in DW, using SQL.In the tabular project (we're i've noticed that these 4 %'s are in itself strange), in a 1st moment i've noticed that i would have to divide by 100 to get the same values as in the DW, so i've used AVERAGEX:

Avg_AMP:=AVERAGEX('Fct Sales';'Fct Sales'[_AMP]/100)
Avg_AMPdollar:=AVERAGEX('Fct Sales';'Fct Sales'[_AMPdollar]/100)
Avg_FMP:=AVERAGEX('Fct Sales';'Fct Sales'[_FMP]/100)
Avg_FMPdollar:=AVERAGEX('Fct Sales';'Fct Sales'[_FMPdollar]/100)

The results were, respectively: 701,68; 2120,60...; -669,441; and  finally **-694,74** for Avg_FMPdollar.i can't understand the difference to SQL calculation, since calculations are similar to the other ones. After that i've tried:

test:=SUM([_FMPdollar])/countrows('Fct Sales') AND the value was EQUAL to SQL: -672,17
test2:=AVERAGE('Fct Sales'[_Frontend Margin Percent ACY]), and here, without dividing by 100 in the end, -696,74...

So, AVERAGE and AVERAGEX have a diferent behaviour from the SUM divided by COUNTROWS, and even more strange, test2 doesn't need the division by 100 to be similar to AVERAGEX result.

I even calculated the number of blanks and number of zeros on each column, could it be a difference on the denominator (so, a division by a diferente number of rows), but they are equal on each row.

View 2 Replies View Related

Analysis :: SSAS Time Period Dimension Aggregation

Jul 27, 2015

I have a monthly time period dimension representing average number of students for each month. At the yearly aggregate level I don't want it to sum up the avg number of students from every month because that number is incorrect. I would like it to use the number of students from the most recent month as a roll up. Is that possible to configure in SSAS?

View 2 Replies View Related

Analysis :: SSAS - Time Intelligence Is Not Working In Tabular Model

Apr 17, 2015

I have a separate date dimension marked as Date table in Tabular Model and having proper relationship with another table(e.g SalesTable) with column of date type. But still time intelligence functions are not working. I am using the date column from other table (e.g SalesTable) in the formula. What exactly going wrong in our tabular model.

View 3 Replies View Related

Analysis :: SSAS LastnonEmpty Not Showing Data For Entire Time Hierarchy?

Jun 8, 2015

I have a time dimension which has Date, Week, Month and Year. However, the hierarchy will have only Week, Month and Year. It works great for any Sales measure with AggregateFunction as SUM.

I have created a new measure with AggregateFunction = LastNonEmpty. Also in the backend, I have pushed all the inventory data to last date in every month as inventory is always looked on a monthly basis not on a weekly basis. This measure shows correct data for every last week of the month in the hierarchy. However, Months and Years are displayed as zeros.

what I am doing wrong.

View 8 Replies View Related

Where To Do The Calculation In VB.NET Or In SQL?

May 4, 2008



Hi,

My predicament is - where do I do these calculations - in my vb.net code or in an SQL stored procedure?

My manager has handed me a task of converting an excel file she uses in to a web aplication.

While it has been easy to devise what should be the screens and how to capture data, I am struggling over how to code the calculations.


The calculations in excel are pretty simple. These are just sequential calculations (about a 150 calculation for average 500 rows). Mathametical operations include sum, average, max min - regular excel stuff. Some calculations involve vlookup (equvalent to calculation based on value derived from a reference table).


So I am stil wondering - where do I do these calculations - in my vb.net code or in an SQL stored procedure?


Since these calculations are required a produce a result in an online environment, what will be faster?


I tried to do a proof of concept by creating a sample calculation in a .NET class and an in a stored procedure. The choice is still not clear. SQL code execution time was not bad. But SQL code tended to be very messy.VB.net code seemed to be a little slow. But seemed a more organised to look at.


Any views that you can offer will be very helpful.

Thanks in advance.

PMA

View 6 Replies View Related

Help W/ Calculation

Aug 3, 2007

I need to calculate the overall GPA for a student in a particular class.


YEAR SCHOOL STUDENT IDENT GRADE TEACHER CLASS GPA
2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 0.0000
2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 1.6700
2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 3.3300
2007 Snow Canyon High Student1 321649 10 Teacher1 Earth Systems 3.6700
2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 0.0000
2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 0.6700
2007 Snow Canyon High Student1 321649 10 Teacher2 Elementary Algebra 1.0000


The problem I'm having is that a student may not taken the class for four terms (as in the Elementary Algebra example above). So I can't hard code it to sum the gpa and divide by 4; it needs to be the number of terms the student took the class.


Here's my sql:


select
trnscrpt.schyear as [Year],
school.schname as School,
rtrim(stugrp_active.lastname) + ', ' + rtrim(stugrp_active.firstname) as Student,
trnscrpt.suniq as suniq,
stugrp_active.graden as Grade,
trnscrpt.teachname as Teacher,
trnscrpt.descript as Class,
gpamarks.gpavallvl0 AS GPA

from
dbo.trnscrpt
inner join dbo.stugrp_active on trnscrpt.suniq = stugrp_active.suniq INNER JOIN
school ON stugrp_active.schoolc = school.schoolc INNER JOIN
gpamarks ON trnscrpt.marksetc1 = gpamarks.marksetc AND trnscrpt.markawd1 = gpamarks.mark

where
trnscrpt.graden >= 6 and
trnscrpt.markawd1 not in ('NC','NG','P','W','WA','WF','WI','WP') and
trnscrpt.subjectc in ('LA', 'MA', 'CP', 'CB') and
trnscrpt.schyear = 2007 and
stugrp_active.schoolc = 725

order by
school.schname,
student,
grade,
class

View 3 Replies View Related

MDX Calculation Help

May 28, 2008

Dimensions:

DimPeriod/Year-Quarter-Month
DimProduct/Category-Product
Fact:
FactInventory/PeriodKey-ProductKey-StatusCode


Period = 1
Product = 1
Status Code = InStock


Period = 1
Product = 2
Status Code = InStock



Period = 2
Product = 1
Status Code = OutOfStock

Period = 2
Product = 2
Status Code = InStock


In period = 2, status code change from InStock to OutOfStock: Product 1 (Count=1)
In period = 1, number of products with status code = InStock: product 1 and product 2 (Count=2)


The measure = 1 / 2 or 50%. TIA

View 2 Replies View Related

Calculation

Oct 9, 2007



This is a smple data in table1

sector RefDate price
pharm 22 august 2007 100.21
gap 15 august 2007 10.32
pharm 21 august 2007 99.99
pharm 9 oct 2007 100.99
pharm 2 oct 2007 98.34
pharm 8 oct 2007 96.34
...

I would like to have the result as follows:
sector RefDate price priceChangeSinceYesterday priceChangeSinceLastWeek priceChangeSinceLastMonth
pharm 9 oct 2007 100.99 100.99-96.34 100.99-98.34 100.99-lastmonth's price value

select
sector,
RefDate,
price,
priceChangeSinceYesterday??,
priceChangeSinceLastWeek???,
priceChangeSinceLastMonth??
from
table1

thanks

View 3 Replies View Related

Calculation

Apr 2, 2008



My aim is to do something like what I have explained below and I was planning on building this logic at the Database level only rather than on the frontend code.

There are certain allocations(transactions) that happen on a periodic basis and I am storing these transactions in the PurchaseTranMaster and PurchaseTranDetail table. These transactions are categorized as 'Main' type and the amount could be allocated for one or many categories in a single transaction. Below is how it will be saved in the 2 table


PurchaseTranMaster


TranID TranDate TranType
1 14-March-2008 Main
2 17-March-2008 Main
3 1 9-March-2008 Main


PurchaseTranDetail



TranID Amount Category Debit_TranId
1 1000 A
1 1000 B
2 2000 B
3 300 A
3 400 C


Now what happens is users of my application can make purchases under all these categories only until the Balance under these categories is > than purchase amount. The Balance is calculated as sum of all transactions. It means that w.r.t the above data the balances for each category is(this is not stored in the database)

A 1300
B 3000
C 400

So lets say a user does make a purchase(Trantype is 'SUB') of 300 under A and 400 under B in a single transaction. The data would then be stored in the tables as


PurchaseTranMaster


TranID TranDate TranType
1 14-March-2008 Main
2 17-March-2008 Main
3 19-March-2008 Main
4 20-March-2008 SUB


PurchaseTranDetail


TranID Amount Category Debit_TranId
1 1000 A
1 1000 B
2 2000 B
3 300 A
3 400 C
4 300 A 1
4 400 B 1


In the PurchaseTranDetail the Debit_TranId value means that the amount has been marked against the TranID 1. This TranId is not handpicked by the user and the system should allocate it accordingly based on the amount available for a particualar category for a Main Transaction. It means that before TranId 4 was saved in the database then the system would first check whether the Total available balance for A >=300 and B>=400 (in our example above it is 1300 and 3000 resp)
Then if the Balance is > than the puchase amount then the allocation would be done by the system and this would be done against the TranID whose TranDate was the earliest, so thats why the Debit_TranId column has 1 as TranId 1 was the earliest.so logically now the balance for the categories would be (this is not saved in the database)

A 1000
B 2600
C 400

So next time again when a user would make a purchase(transaction) under A for 800 and under B for 1000 then if the balance is greater than the purchase amount(which in this case it is) the allocation would happen according to the earliest TranId and this time amount would be partly marked against TranId 1 , TranID 2 and TranID 3. The data would look like this


PurchaseTranMaster


TranID TranDate TranType
1 14-March-2008 Main
2 17-March-2008 Main
3 19-March-2008 Main
4 20-March-2008 SUB
5 21-March-2008 SUB



TranID Amount Category Debit_TranId
1 1000 A
1 1000 B
2 2000 B
3 300 A
3 400 C
4 300 A 1
4 400 B 1
5 700 A 1
5 100 A 3
5 600 B 1
5 400 B 2


I need to do the above taking into consideration that there could be multiple users making purchases(concurrency).
Also I was building my logic on doing the above whether to use cursors or loops. I just need to know how do I write my stored procedure and what would be the most efficeint way of doing the above.

The design for creating the above sample tables is below

/*CREATE TABLE PurchaseTranMaster
(
TranID int IDENTITY(1,1) PRIMARY KEY CLUSTERED,
TranDate Datetime,
TranType varchar(30)
)


CREATE TABLE PurchaseTranDetail
(
TranID int,
Amount int,
Category Varchar(20),
Debit_TranId int
)

insert into PurchaseTranMaster values(convert(datetime,' 14-March-2008',103),'Main')
insert into PurchaseTranMaster values(convert(datetime,' 17-March-2008',103),'Main')
insert into PurchaseTranMaster values(convert(datetime,' 19-March-2008',103),'Main')
insert into PurchaseTranMaster values(convert(datetime,' 20-March-2008',103),'SUB')
insert into PurchaseTranMaster values(convert(datetime,' 21-March-2008',103),'SUB')


insert into PurchaseTranDetail values(1,1000,'A',0)
insert into PurchaseTranDetail values(1,1000,'B',0)
insert into PurchaseTranDetail values(2,2000,'B',0)
insert into PurchaseTranDetail values(3,300,'A',0)
insert into PurchaseTranDetail values(3,400,'C',0)
insert into PurchaseTranDetail values(4,300,'A',1)
insert into PurchaseTranDetail values(4,400,'B',1)
insert into PurchaseTranDetail values(5,700,'A',1)
insert into PurchaseTranDetail values(5,100,'A',3)
insert into PurchaseTranDetail values(5,600,'B',1)
insert into PurchaseTranDetail values(5,400,'B',2)*/

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved