Thursday, March 29, 2012
Calculated Member help
[Measures].[Sales]/Descendants([TIME_WEEK_DIM],[TIME_WEEK_DIM].[Time Week Desc]).count
The problem with this is that it works only if the user select a single time member. I am using Excel as frontend and I fixed the pivot table in such a way that Sales is on the column, and Store is on the Rows. The time dimension is on the top serving as filter (Page axis). Because you can choose multiple dimension member in the dropdown boxes of any dimension in Excel, I am having trouble making it work in these scenario. It only works if you select one time member at a time. Please help.I don't fully understand what you are trying to do, but since the database server is returning a simple dataset to your Excel pivot table, the problem would appear to be with the pivot table and not the query or table you are using. When you filter the pivot table you are fiiltering its stored snapshot of the query results. It does not pass the parameters back to the database server.
blindman|||Hi, thnks so much for the reply. Anyway, to make it clear to you:
I'm using an Analysis Service Cube as my backend and Excel Pivot table as my frontend.
I have two dimension in my cube: 1. Time(Yr, Qtr, Month, Week) and 2. Store
I have two measures: 1. Sales and 2. Sales per week (this measure is a calculated member
The formula I use to make the Sales per week measure is:
[Measures].[Sales]/Descendants([TIME_WEEK_DIM],[TIME_WEEK_DIM].[Time Week Desc]).count
Here's my setup in Excel: The sales is broken down by store and the time is on top acting as a filter
Time: 2003
Store Sales Sales/Week
Store1 100 25
Store2 200 12
My problem occurs evrytime the user selects more than one Time value to filter on (like all Jan AND Feb data). It works only if one time value is selected at a time. When user chooses more than 1 time value, the Sales/Week data appears as: #Num!|||Sorry smb, but I don't have experience with data cubes syntax. Hopefully now that your post is at the top of list someone else will check it out and give you an answer!
blindman|||Thnks anyway blindman :)
Tuesday, March 27, 2012
Calculated member - please help (SQL Server 2000)
please if u could help with this:
i have a cube with 3 dimensions, Sales (fact table), Time and Accounts (general ledger accounts). Accounts dimension hierarchy is as follows:
1. Revenues
1.1 Income
1.1.1 number of account in General Ledger
1.1.2 number of account in GL etc.....
2. Expenses
2.1 Fixed costs
2.1.1 number of account in GL etc....
2.2 Operating costs
2.3 Overhead
3. Unsorted
now what i need to do is next: i need to calculate measure.salesamount in percentage of total sales amount for each category of accounts. for example i need measure.salesamount of each account number in Revenue/Income in percentage of the total salesamount of the category Revenue.
i hope i was clear enough in what i need.
please can anyone help me with this?
thank you in advance!
marko
try an expression something like the following in your calculation:
Measures.salesAmount / (Measures.salesAmount,Accounts.CurrentMember.Parent)
You can then either wrap the whole thing in brackets and mulitply by 100 or you should be able to use a percentage style format string - it depends a bit on how your front end works.
|||Hello Marko,i am not 100% clear on ur pblm. but on what ever i understood i have given u a formula for calculating the calculated-member.
iif(
[revenue_dimension].currentmember.parent is null,1, ( [revenue_dimension].currentmember , [measures].[salesamount] ) / ([revenue_dimension].currentmember.parent , [measures].[salesamount] )
)
then make the data type of this calculated-member to percentage.
regards,
Rajiv.|||
Hi,
thank you both for your answers. both formulas work and give the same result.
Thank you once again for your help! Much appreciated!
best regards
marko
Calculated measures in report builder
Any help is appreciated.
You can't. The Report Builder doesn't fetch dimension calculated members. For this reason, we abandoned dimension calculated members and defined them as calculated measures in the cube. I wasn't successful also in trying to define the calculated dimension members as regular members by implementing an utility dimension because cells that do not exists in the cube cannot be written to.|||Thanks for your response, Teo.
Are you saying that you couldn't do it at all, or that you were able to convert the time calcs to calculated measures and you were then able to use them in Report Builder? At the moment I'm not sure how I would go about converting the time calcs to calculated measures.
BTW, I read your book. Nice work!
|||Thanks. The calculated mesures approached worked but you will end up with as many calculated measures as the number of the time-based calculations (QTD, YTD, etc.). Another issue you will discover if you decide to take this road is that a date filter in the RB report won't overwrite the default member fo the Date dimension. This will force you to always bring the Date dimension in the report if the report uses the time calculated measures.
What I wasn't able to do is implement the Time intelligence dimension calculated members as regular members of an utility dimension.
It will be great if you could log this issue to connect.microsoft.com. The more it is asked for the more likely will be to get implemented.
|||Hi,
I want to generate Ad-Hoc reports using report builder with cube created. But am not able to see any calculated measures in the report. Can anyone tell me how to solve this.
|||You need to assign the calculated measures to display folders using the Properties window on the Calculations tab.sqlCalculated measure using Tail/Filter on time not always working
We created the following time based measure to get the distinct count of propertyId - but we needed to get the distinct count from the last fact table load in a time period so we used the following
Code Snippet
IIF([Time].Currentmember.level.ordinal = 4, [Measures].[Property Id],
IIF([Time].Currentmember.level.ordinal = 3,
(tail(filter([Time].Currentmember.children, NOTISEMPTY([Measures].[Number of Buildings])), 1).item(0), [Measures].[Number of Buildings]),
IIF([Time].Currentmember.level.ordinal = 2,
IIF([Time].Currentmember.properties("Is Quarter") = "1",
(tail(filter([Time].Currentmember.children, NOTISEMPTY([Measures].[Number of Buildings])), 1).item(0), [Measures].[Number of Buildings]), ([Time].Currentmember.lastchild, [Measures].[Number of Buildings])),
IIF([Time].Currentmember.level.ordinal = 1,
IIF([Time].Currentmember.properties("Is Year") = "1",
(tail(filter([Time].Currentmember.children, NOTISEMPTY([Measures].[Number of Buildings])), 1).item(0), [Measures].[Number of Buildings]), ([Time].Currentmember.lastchild, [Measures].[Number of Buildings])),
IIF([Time].Currentmember.level.ordinal = 0,
(tail(filter([Time].Currentmember.children, NOTISEMPTY([Measures].[Number of Buildings])), 1).item(0), [Measures].[Number of Buildings]),
NULL
)))))
In most cases, the calculation seems to work fine, but sometimes, when browsing the cube using Proclarity (6.1), no values are returned when we know there are values...
Can anyone see why this measure would not work in some circumstances?
I think that basically, what I'm asking for is a method of determining a distinct count of the last recordset from a fact table for any time dimension level (which is what the above is trying to do).
The above method seems only to work rather haphazardly, especially when viewing via Proclarity (6.1) When you move certain dimensions to the background, the calculation returns zero when we knbow data exists...
Is there a more efficient way of finding this sort of distinct count (using SQL 2000) ?
|||Anyone fancy a stab at this ?|||Hi,
have not read the whole mdx,
do not know proclarity
This does not work if you do a multiselect on the time dimension beause of CurrentMember (there is no current member if you have a subquery)
Does it return null or #error and do not show up.
It really depends on how your client does write his queries. I would recomend you trace your queries with profiler and then analyse the query which is returning wrong results. Check where and how the measure is used and check if there are any subqueries based on time.
Best Regards, HANNES
|||Thanks for having a look at this
The following query will not return any values for No of Buildings
Code Snippet
SELECT { [Measures].[Number of Units], [Measures].[Number of Buildings], [Measures].[Property Id] } ON COLUMNS ,
{ DESCENDANTS( [Building Status].[All Building Status], [Building Status].[Building Status] ) } ON ROWS
FROM [Property]
WHERE ( [Time].[Year].&[2007] )
I can't really see why not, as it should pick up the latest data for 2007 should it not, given the calculations in my first post ?
|||Hi,
I am a little bit confused about the complexity...
A few more questions.
Do you have only one Hierarchy in Time? (All Attribute hierarchies are hidden - I guess yes because you do not specify an hierarchy name)
Is it a 2005 cube or 2000?
Are the properties populated correct? Is Quarter, Is Year
Why you need this properties - if its one hierarchy then level 2 could only be quarters? and level 1 only years and level 0 only ALL if I am right
Why do you write this complex form - why not only decendants(time.currentmember),time.levels.count, leaves) which your tail logic
maybe one of this is a hint to you.
HANNES
PS: I would alos recommend moshas blog with design time level checking instad of runtime level checking. Scope instead of member with iif (only for design purpose - have nothing to do with functionality)
|||Hi,
1. SQL 2000 cubes - and yes, the properties are all fine and we can't change time dimension at this stage as it works fine itself.
It's this complex because we have daily loading in certain parts of DW but weekly in others - in terms of a measure using distinct count
this presents issues when querying measures from weekly loads in terms of needing to hit the last load in a period, be it month, quarter, year or All Time...
In any case we fixed the issue by creating a completely new view for building count as we read that distinct count runs in to known issues when AGGREGATE used in MDX queries, so in developing the new view we populated a 1 for propertyid as opposed to attempting to do a distinct count - also we created calculated cells to deal with the time hierarchy levels issue - we then based a new cube containing just building count but shared same dimensions with the old cube, containing other aggregateable valid measures that worked.
Megred the two cubes into a new virtual cube & now building count works fine So problem solved. I think the tail/filter issue was a red herring in any case - the data that got was fine - AS 2000 just does not like distinct counts (in the way we were trying to use them...)
Thanks for getting involved with this though, but i'll mark it as solved for now.
Sunday, March 25, 2012
Calculated Measure does not appear in all the drilldowns
Hello,
I created a hierarchy [Time].[Year-Month] that has the following
-Year
--Period
English Month
I want to return the headcount from the 1st Period only. This works fine. I did it by making a new measurement called LastActive by using the LastNonEmpty aggregate function. I then made a calculated measure called BeginHeadCount as the following:
([Measures].[LastActive], [Time].[Period].&[1]). This works OK, sort of.
When I browse the cube, and I put the [Time].[Year-Month] hierarchy on the columns I don’t see the BeginHeadCount for each English Month, but I do see it for the totals. For example, I see the BeginHeadCount for the Year, then I hit the + and drill-down to the Period, I see it in Period, I hit the + again to drill-down to the English Month – the breakout is now English Month and Total. The Total does show the BeginHeadCount but it is blank in the English Month.
How do I get the BeginHeadCount calculated measure to also appear in the English Month?
I assume that this has something to do with referring specifically to the &[1] period. But I don’t know how to resolve this.
Thank you for the help.
Your issue here is that you have specified a tuple to calculate your value.
A tuple can best be described as an intersection in multi-dimensional space, so what you are essentially saying is to return the [BeginHeadCount] measure where Period.&[1] intersects with each of the members in the current query. What this gives you are intersections where no data exists such as period 1 and month 12.
I am guessing that what you really want to say is "regardless of the current time members, show me the amount from Period 1". You would do this by using an aggregate function that will return a numeric amount from the calculation rather than a tuple. Something like the following should do the trick, you would have to include the current member from the year attribute in the calcuation so that it does not sum up period 1 for every year (which would not make any sense).
|||SUM( {([Time].[Year].CurrentMember,[Time].[Period].&[1])}, [Measures].[LastActive])
You didn't describe the attribute relationships among the attributes: [Year], [Period] and [English Month] of the [Time].[Year-Month] hierarchy. My guess is that this isn't a natural hierarchy - if [Period] is like [Quarter Of Year] and [English Month] like [Month Of Year] in the Adventure Works [Date] dimension, you might try:
([Measures].[LastActive], [Time].[Period].&[1], [Time].[English Month].[All])
|||Darren/Deepak,
Thank you for the great answers. They were both a great help. I am now able to see the data the way I wanted to.
Another quick question... Deepak, when you say that it was your guess that the relationships between the attributes wasn't a natural hierarchy, what do you mean by that? I did create a new hierarchy that has the Year-Period-English month. Is this different then a natural hierarchy? What make a natural hierarchy?
Thanks for the information. Hopefully my new MDX book will come this week and I wont ask these newbie questions
"What make a natural hierarchy?" - here's an entry from Mosha's blog which discusses this:
http://sqljunkies.com/WebLog/mosha/archive/2006/11/09/natural_hierarchy.aspx
>>
What are the natural hierarchies and why they are a good thing
...
A natural hierarchy is composed of attributes where each attribute is a member property of the attribute below. For example, the Geography hierarchy Country, State, City and Name is a natural hierarchy if City is a member property of Name; State is for City; and Country is for State. The hierarchy Gender-Age is not a natural hierarchy because Gender is not a member property of Age.
...
It should be clear by now, that whenever possible, unnatural hierarchies should be avoided. But this doesn't mean that unnatural hierarchies are always bad ! Any guidance should be considered within its reasoning. For example, in my article about Time Calculations in UDM, I showed how using unnatural hierarchies in the form Year -> QuarterOfYear -> MonthOfQuarter -> DayOfMonth, actually simplifies a lot writing time relation calculations.
...
>>
|||Thank you for all your help!Calculated Measure does not appear in all the drilldowns
Hello,
I created a hierarchy [Time].[Year-Month] that has the following
-Year
--Period
English Month
I want to return the headcount from the 1st Period only. This works fine. I did it by making a new measurement called LastActive by using the LastNonEmpty aggregate function. I then made a calculated measure called BeginHeadCount as the following:
([Measures].[LastActive], [Time].[Period].&[1]). This works OK, sort of.
When I browse the cube, and I put the [Time].[Year-Month] hierarchy on the columns I don’t see the BeginHeadCount for each English Month, but I do see it for the totals. For example, I see the BeginHeadCount for the Year, then I hit the + and drill-down to the Period, I see it in Period, I hit the + again to drill-down to the English Month – the breakout is now English Month and Total. The Total does show the BeginHeadCount but it is blank in the English Month.
How do I get the BeginHeadCount calculated measure to also appear in the English Month?
I assume that this has something to do with referring specifically to the &[1] period. But I don’t know how to resolve this.
Thank you for the help.
Your issue here is that you have specified a tuple to calculate your value.
A tuple can best be described as an intersection in multi-dimensional space, so what you are essentially saying is to return the [BeginHeadCount] measure where Period.&[1] intersects with each of the members in the current query. What this gives you are intersections where no data exists such as period 1 and month 12.
I am guessing that what you really want to say is "regardless of the current time members, show me the amount from Period 1". You would do this by using an aggregate function that will return a numeric amount from the calculation rather than a tuple. Something like the following should do the trick, you would have to include the current member from the year attribute in the calcuation so that it does not sum up period 1 for every year (which would not make any sense).
|||SUM( {([Time].[Year].CurrentMember,[Time].[Period].&[1])}, [Measures].[LastActive])
You didn't describe the attribute relationships among the attributes: [Year], [Period] and [English Month] of the [Time].[Year-Month] hierarchy. My guess is that this isn't a natural hierarchy - if [Period] is like [Quarter Of Year] and [English Month] like [Month Of Year] in the Adventure Works [Date] dimension, you might try:
([Measures].[LastActive], [Time].[Period].&[1], [Time].[English Month].[All])
|||Darren/Deepak,
Thank you for the great answers. They were both a great help. I am now able to see the data the way I wanted to.
Another quick question... Deepak, when you say that it was your guess that the relationships between the attributes wasn't a natural hierarchy, what do you mean by that? I did create a new hierarchy that has the Year-Period-English month. Is this different then a natural hierarchy? What make a natural hierarchy?
Thanks for the information. Hopefully my new MDX book will come this week and I wont ask these newbie questions
"What make a natural hierarchy?" - here's an entry from Mosha's blog which discusses this:
http://sqljunkies.com/WebLog/mosha/archive/2006/11/09/natural_hierarchy.aspx
>>
What are the natural hierarchies and why they are a good thing
...
A natural hierarchy is composed of attributes where each attribute is a member property of the attribute below. For example, the Geography hierarchy Country, State, City and Name is a natural hierarchy if City is a member property of Name; State is for City; and Country is for State. The hierarchy Gender-Age is not a natural hierarchy because Gender is not a member property of Age.
...
It should be clear by now, that whenever possible, unnatural hierarchies should be avoided. But this doesn't mean that unnatural hierarchies are always bad ! Any guidance should be considered within its reasoning. For example, in my article about Time Calculations in UDM, I showed how using unnatural hierarchies in the form Year -> QuarterOfYear -> MonthOfQuarter -> DayOfMonth, actually simplifies a lot writing time relation calculations.
...
>>
|||Thank you for all your help!Calculated Measure does not appear in all the drilldowns
Hello,
I created a hierarchy [Time].[Year-Month] that has the following
-Year
--Period
English Month
I want to return the headcount from the 1st Period only. This works fine. I did it by making a new measurement called LastActive by using the LastNonEmpty aggregate function. I then made a calculated measure called BeginHeadCount as the following:
([Measures].[LastActive], [Time].[Period].&[1]). This works OK, sort of.
When I browse the cube, and I put the [Time].[Year-Month] hierarchy on the columns I don’t see the BeginHeadCount for each English Month, but I do see it for the totals. For example, I see the BeginHeadCount for the Year, then I hit the + and drill-down to the Period, I see it in Period, I hit the + again to drill-down to the English Month – the breakout is now English Month and Total. The Total does show the BeginHeadCount but it is blank in the English Month.
How do I get the BeginHeadCount calculated measure to also appear in the English Month?
I assume that this has something to do with referring specifically to the &[1] period. But I don’t know how to resolve this.
Thank you for the help.
Your issue here is that you have specified a tuple to calculate your value.
A tuple can best be described as an intersection in multi-dimensional space, so what you are essentially saying is to return the [BeginHeadCount] measure where Period.&[1] intersects with each of the members in the current query. What this gives you are intersections where no data exists such as period 1 and month 12.
I am guessing that what you really want to say is "regardless of the current time members, show me the amount from Period 1". You would do this by using an aggregate function that will return a numeric amount from the calculation rather than a tuple. Something like the following should do the trick, you would have to include the current member from the year attribute in the calcuation so that it does not sum up period 1 for every year (which would not make any sense).
|||SUM( {([Time].[Year].CurrentMember,[Time].[Period].&[1])}, [Measures].[LastActive])
You didn't describe the attribute relationships among the attributes: [Year], [Period] and [English Month] of the [Time].[Year-Month] hierarchy. My guess is that this isn't a natural hierarchy - if [Period] is like [Quarter Of Year] and [English Month] like [Month Of Year] in the Adventure Works [Date] dimension, you might try:
([Measures].[LastActive], [Time].[Period].&[1], [Time].[English Month].[All])
|||Darren/Deepak,
Thank you for the great answers. They were both a great help. I am now able to see the data the way I wanted to.
Another quick question... Deepak, when you say that it was your guess that the relationships between the attributes wasn't a natural hierarchy, what do you mean by that? I did create a new hierarchy that has the Year-Period-English month. Is this different then a natural hierarchy? What make a natural hierarchy?
Thanks for the information. Hopefully my new MDX book will come this week and I wont ask these newbie questions
"What make a natural hierarchy?" - here's an entry from Mosha's blog which discusses this:
http://sqljunkies.com/WebLog/mosha/archive/2006/11/09/natural_hierarchy.aspx
>>
What are the natural hierarchies and why they are a good thing
...
A natural hierarchy is composed of attributes where each attribute is a member property of the attribute below. For example, the Geography hierarchy Country, State, City and Name is a natural hierarchy if City is a member property of Name; State is for City; and Country is for State. The hierarchy Gender-Age is not a natural hierarchy because Gender is not a member property of Age.
...
It should be clear by now, that whenever possible, unnatural hierarchies should be avoided. But this doesn't mean that unnatural hierarchies are always bad ! Any guidance should be considered within its reasoning. For example, in my article about Time Calculations in UDM, I showed how using unnatural hierarchies in the form Year -> QuarterOfYear -> MonthOfQuarter -> DayOfMonth, actually simplifies a lot writing time relation calculations.
...
>>
|||Thank you for all your help!sqlCalculated Measure
Hi,
I am trying to create a calculated measure called revenue which is equal to the hourly rate of an item mutiplied by the time the item is used for.
Engine hours is a measure within the fact table and hourly rate is a attribute of one of my dimensions. If i set the calculated measure simply to the value of the hourly rate (Asset Dimension) when the measure revenue is displayed in the cube no data is shown even though i know data should be shown.
Do have any explanation for this?
Cheers,
Unless you have selected a particular Asset which has an hourly rate, the context of the Asset dimension is probably at the [All] member which does not have an hourly rate.
You could:
1) calculate the hourly rate in MDX using something like SUM(EXISTING [Asset].[Asset].[Hourly Rate], [Asset].[Asset].[Hourly Rate].memberValue)
2) You could make the Asset table play the role of a fact and dimension. Then you could use a member expression to calculate the revenue. This should give you pretty good performance too. I think the Adventure Works sample database uses measure expression for some of it's currency conversion stuff.
|||Thanks for the Reply,
Several Questions:
Firstly I had selected a particular asset which had an hourly rate but the hourly rate still did not show.
How do I make my asset table play the role of a fact and dimension table?
Is it possible to within a calculated measure use an attribute from the fact table (Engine Hours) and mutiplie this with an attribute in a dimension (Hourly Rate of Asset)?
Cheers,
|||
medphis wrote:
Firstly I had selected a particular asset which had an hourly rate but the hourly rate still did not show.
Hmm, might be something to do with data types. Have you tried using the .MemberValue function or wrapping the .CurrentMember in a call to the Val() function?
medphis wrote:
How do I make my asset table play the role of a fact and dimension table?
In the Cube structure window you create a new measure group and select the Asset dimension table.
medphis wrote:
Is it possible to within a calculated measure use an attribute from the fact table (Engine Hours) and mutiplie this with an attribute in a dimension (Hourly Rate of Asset)?
Yes, you would normally do something like [Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue. But you would need to make sure that this is executed at a level where the individual hourly rates are available. It's hard to be sure without knowing more, but maybe it would need to look something like this:
SUM(EXISTING [Asset].[Asset].[Hourly Rate] ,[Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue)
|||Hi,
Thanks again for your help, the expression: SUM(EXISTING [Asset].[Asset].[Hourly Rate] ,[Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue) will correctly calculate the revenue at the level of 'Hourly Rate' but the grand total within the cube and when the hourly rate attribute from the asset dimension has not been added to the cube then the error '#Value ' appears within the intersections for the measure Revenue saying:
The following system error occured: Type mismatch... Query(3, 37). There is a type mismatch for the '*' operator.
Both the hourly rate and engine hours are of type decimal and if there is no data for either of these values then a 0.00 is inserted instead of a Null which was done to try and aviod and issue like this.
I am a little unsure as to the approach i should take to debug such an issue?
Your help is appreciated.
Cheers,
|||You would not need to insert 0.00 for the engine hours measure as SSAS does not do null propagation like SQL does and it inherantly evaulates null/empty measures as 0 (if it did not do this, every measure would pretty much be null at the top level). But it is probably wise to do this for the Hourly Rate attribute.
Looking at the code again I think the problem might be the use of the [Asset].[Asset] hierarchy. This looks like it might be a user defined hierarchy and if it is, it would be possible to have a context which is something other than an hourly rate which would lead to EXISTING [Asset].[Asset].[Hourly Rate] returning an empty set which might be the cause of the type mismatch.
Try using something like this:
SUM(EXISTING [Asset].[Hourly Rate].[Hourly Rate] ,[Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue)
PS. Sorry for the delay in replying, I have been on holidays.sqlCalculated Measure
Hi,
I am trying to create a calculated measure called revenue which is equal to the hourly rate of an item mutiplied by the time the item is used for.
Engine hours is a measure within the fact table and hourly rate is a attribute of one of my dimensions. If i set the calculated measure simply to the value of the hourly rate (Asset Dimension) when the measure revenue is displayed in the cube no data is shown even though i know data should be shown.
Do have any explanation for this?
Cheers,
Unless you have selected a particular Asset which has an hourly rate, the context of the Asset dimension is probably at the [All] member which does not have an hourly rate.
You could:
1) calculate the hourly rate in MDX using something like SUM(EXISTING [Asset].[Asset].[Hourly Rate], [Asset].[Asset].[Hourly Rate].memberValue)
2) You could make the Asset table play the role of a fact and dimension. Then you could use a member expression to calculate the revenue. This should give you pretty good performance too. I think the Adventure Works sample database uses measure expression for some of it's currency conversion stuff.
|||Thanks for the Reply,
Several Questions:
Firstly I had selected a particular asset which had an hourly rate but the hourly rate still did not show.
How do I make my asset table play the role of a fact and dimension table?
Is it possible to within a calculated measure use an attribute from the fact table (Engine Hours) and mutiplie this with an attribute in a dimension (Hourly Rate of Asset)?
Cheers,
|||
medphis wrote:
Firstly I had selected a particular asset which had an hourly rate but the hourly rate still did not show.
Hmm, might be something to do with data types. Have you tried using the .MemberValue function or wrapping the .CurrentMember in a call to the Val() function?
medphis wrote:
How do I make my asset table play the role of a fact and dimension table?
In the Cube structure window you create a new measure group and select the Asset dimension table.
medphis wrote:
Is it possible to within a calculated measure use an attribute from the fact table (Engine Hours) and mutiplie this with an attribute in a dimension (Hourly Rate of Asset)?
Yes, you would normally do something like [Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue. But you would need to make sure that this is executed at a level where the individual hourly rates are available. It's hard to be sure without knowing more, but maybe it would need to look something like this:
SUM(EXISTING [Asset].[Asset].[Hourly Rate] ,[Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue)
|||Hi,
Thanks again for your help, the expression: SUM(EXISTING [Asset].[Asset].[Hourly Rate] ,[Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue) will correctly calculate the revenue at the level of 'Hourly Rate' but the grand total within the cube and when the hourly rate attribute from the asset dimension has not been added to the cube then the error '#Value ' appears within the intersections for the measure Revenue saying:
The following system error occured: Type mismatch... Query(3, 37). There is a type mismatch for the '*' operator.
Both the hourly rate and engine hours are of type decimal and if there is no data for either of these values then a 0.00 is inserted instead of a Null which was done to try and aviod and issue like this.
I am a little unsure as to the approach i should take to debug such an issue?
Your help is appreciated.
Cheers,
|||You would not need to insert 0.00 for the engine hours measure as SSAS does not do null propagation like SQL does and it inherantly evaulates null/empty measures as 0 (if it did not do this, every measure would pretty much be null at the top level). But it is probably wise to do this for the Hourly Rate attribute.
Looking at the code again I think the problem might be the use of the [Asset].[Asset] hierarchy. This looks like it might be a user defined hierarchy and if it is, it would be possible to have a context which is something other than an hourly rate which would lead to EXISTING [Asset].[Asset].[Hourly Rate] returning an empty set which might be the cause of the type mismatch.
Try using something like this:
SUM(EXISTING [Asset].[Hourly Rate].[Hourly Rate] ,[Measures].[Engine Hours] * [Asset].[Asset].[Hourly Rate].MemberValue)
PS. Sorry for the delay in replying, I have been on holidays.Calculated Fields in an OLAP cube severly impact data retrieval time
calculated measures in it. When I add the calculated measures to my report
the retrieval time goes from ~1 second to ~4 minutes. I haven't been able
to locate any information about this issue. Is there something I'm doing
wrong, or is this a Reporting services issue?Nevermind. I hadn't realized that splitting a calculated field over an
unrelated dimension would have the same effect.
"Jeremy Farnham" <jeremy.farnham@.omya.com> wrote in message
news:esFYjweBIHA.4712@.TK2MSFTNGP04.phx.gbl...
>I have a OLAP cube that I'm using for a data source that has several
>calculated measures in it. When I add the calculated measures to my report
>the retrieval time goes from ~1 second to ~4 minutes. I haven't been able
>to locate any information about this issue. Is there something I'm doing
>wrong, or is this a Reporting services issue?
>sql
Thursday, March 22, 2012
calculated DistinctCount over two levels of "incomplete" weeks
I have a cube on as2005 where my Time dimension has 5 levels(year, month, quarter, week, day) and a measure that is a distinct count of customers (I also have a customer dimension, with 1 level: customer)
In my time dim, I have "incomplete" weeks, for example the week 32 exist on both august and september months, 5 days of the week in august and 2 days in september.
So at week level I get the distinct customers for that week, for example:
month | week | # distinct customers
AUG | 32 | 15
SEPT | 32 | 20
but, since the week is the same, i want to get the distinct customers for the whole week, and put it on the last month where that week appears, in the example let's say that for week 32 there are 18 different customers, I want a 18 on SEPT.
month | week | # distinct customers
AUG | 32 | NULL
SEPT | 32 | 18
Someone know how can I achieve this?
Thanks!I've found the way to do this, I hope this helps the community!
Aggregate
(
UNION([DM Time].[Hierarchy].CurrentMember.PrevMember.Children,[DM Time].[Hierarchy].CurrentMember.Children)
,[Measures].[# Customers]
)
only for the scope of the week.
Calculated Dimension Member Problem
Hi,
I have a problem that I think I can solve by creating a calculated member in my time dimension, but I am struggling to get it to work.
My time dimension has a hierarchy of Year, Month, Week. The years go from 2002 to 2007, with an additional 'Pre 2002' year (having one month and one week). What I need to do is create an additional year which is the combination of 2002 and 'Pre 2002', which will then be called 'Pre 2003'. I have tried the following:
Code Snippet
CREATE MEMBER CURRENTCUBE.[Time].[Time].[All].[Pre 2003]
AS [Time].[Time].[Year].&[2002] + [Time].[Time].[Year].&[2001], -- (2001 is my name for the pre 2002 member)
VISIBLE = 1 ;
This builds ok, but when I browse the dimension, or use it in Excel 2003, the calculated member is nowhere to be seen.
Any ideas?
Dave
Your formula should be OK. An equivalent calc member for Adventure Works is the following.
create member currentcube.[Date].[Fiscal].[All Periods].[Pre 2004] as
[Date].[Fiscal].[Fiscal Year].&[2002] + [Date].[Fiscal].[Fiscal Year].&[2003];
In order to see your new calculated member you need to make sure you have deployed the changed calculation script to the server. When your said "this builds ok", it gave me an idea that you work in project mode (there is also possibility to work explicitly connected to the server). In the project mode the change you made is related only to the local files on your drive. When you use Build menu item it means that a validation has happened and a deployment script has been created but it does not mean the server already knows your changes. You need to use Deploy menu item in order Visual Studio to send your changes to the server. After that you should see your calculated member in the *new* browser window. If you already had it open you need to select Reconnect button for the change to be visible in the browser window.
In the server online mode (when you work directly with the server) you would just hit Save button and reconnect the browser.
Also, make sure you browse your Time hierarchy of Time dimension. A dimension can have more than one hierarchy. Similarly in Adventure Works i see the member above only when i browse Fiscal hierarchy of the Date dimension but Calendar hierarchy does not have the member.
|||
Andrew,
I am definitely deploying the changes to the server, as any other calculated measures appear correctly.
I have tried using the Adventure Work example you gave, and I have the same problem. In the dimension browser the new period is nowhere to be seen.
|||Ok,
I can now see the calculated member. I was looking in the dimension browser instead of the cube browser!! Now I have another problem. I am connecting to the cube from Excel 2003, and when I drag in the hierarchy I cannot see the new member. In Excel 2007 there is a pivot table property "show calculated members from OLAP server" When I set this I can see the member fine. However, I need to use Excel 2003 for this project. I have found a pivot table property "ViewCalculatedMembers" which I have set to true using VBA. However, the member still does not appear.
Any ideas?
calculated columns in a table
I have a table with fields FirstName and LastName. I also have a column
FullName. Each time the table is updated, I'd like the field FullName
to be calculated automatically based on the values of FirstName and
LastName (FullName = FirstName + ' ' + LastName).
What Default value should I enter when I design the table ?
Thankscreate table test1 ( firstnm varchar(10),
lastname varchar(10),
fullname as firstnm + ' ' + lastname
)
insert into test1 (firstnm,lastname) values ('Omni','buzz')
select * from test1
-Omni|||Thanks. that answers my question :)
Omnibuzz wrote:
> create table test1 ( firstnm varchar(10),
> lastname varchar(10),
> fullname as firstnm + ' ' + lastname
> )
>
> insert into test1 (firstnm,lastname) values ('Omni','buzz')
> select * from test1
> -Omni
Calculate values between previous rows
saved me tons of development time. I am trying to calculate values
between previous rows in my table. The table looks something like
this:
ID Value
1 100
2 200
3 300
4 400
5 ?
I was wondering if there was a way to create an expression that would
calculate the difference between row 4 and row 1. I am expecting row 5
to be 300. I have looked at the previous function, but this does not
seem to be what I am looking for. Any ideas?
Thank you,
Scott Leandro
scottleandro_@.gmail.com (remove the _)save row1 value into a variable and then subtract from it
i.e.
set @.myValue = select value from table where ID = 1
then
select id , value -@.myvalue
from xxx
you might have to work around your design so that value for ID =1 won't
return 0
ken
scottleandro@.gmail.com wrote:
> First, thanks to all of those that post to this newsgroup. You've
> saved me tons of development time. I am trying to calculate values
> between previous rows in my table. The table looks something like
> this:
> ID Value
> 1 100
> 2 200
> 3 300
> 4 400
> 5 ?
> I was wondering if there was a way to create an expression that would
> calculate the difference between row 4 and row 1. I am expecting row 5
> to be 300. I have looked at the previous function, but this does not
> seem to be what I am looking for. Any ideas?
> Thank you,
> Scott Leandro
> scottleandro_@.gmail.com (remove the _)|||SQLKen,
Thanks for the reply. I wish I could do this in a SP, but
unfortunately I have to to do this calculation in a RS table cell
expression.
Thanks,
Scott
SQLKen wrote:
> save row1 value into a variable and then subtract from it
> i.e.
> set @.myValue = select value from table where ID = 1
> then
> select id , value -@.myvalue
> from xxx
> you might have to work around your design so that value for ID =1 won't
> return 0
> ken
>
> scottleandro@.gmail.com wrote:
> > First, thanks to all of those that post to this newsgroup. You've
> > saved me tons of development time. I am trying to calculate values
> > between previous rows in my table. The table looks something like
> > this:
> >
> > ID Value
> > 1 100
> > 2 200
> > 3 300
> > 4 400
> > 5 ?
> >
> > I was wondering if there was a way to create an expression that would
> > calculate the difference between row 4 and row 1. I am expecting row 5
> > to be 300. I have looked at the previous function, but this does not
> > seem to be what I am looking for. Any ideas?
> >
> > Thank you,
> > Scott Leandro
> > scottleandro_@.gmail.com (remove the _)sql
Calculate Time Off
I need a query that can return the total time off between 2 dates.
I have a table call tblTimeOff which has the following fields
StartTimeOff, Interval (minute), W
Sample data for tblTimeOff:-
10.00AM, 15, 0 - Timeoff period 10.00am to 10.15am on W
12.00pm, 60, 0 - Timeoff period 12.00pm to 1.00pm on W
15.00pm,15, 0 - - Timeoff period 3.00pm to 3.15pm on W
10.30AM, 15, 1 - Timeoff period 10.30am to 10.45am on W
12.30pm, 60, 1 - Timeoff period 12.30pm to 1.30pm on W
Saturday and Sunday are considered as W
Mon - Fri are W
I need a query when user provide me with 2 date:-
Condition 1:
--
Start :- 2nd March 8.30am
End :- 4th March 11.00am
The result for total time off should be:- 195 mins
2nd March - 15+60+15, 3rd March - 15+60+15, 4th March (w
Condition 2:
--
Start :- 2nd March 8.30am
End :- 2nd March 5.00pm
The result for total time off should be:- 90 mins
2nd March - 15+60+15
Anyone help ?
Thank You,
mfwooWhere are your dates stored in your tables?
Posting the full DDL may help.
http://www.aspfaq.com/etiquette.asp?id=5006
"Woo Mun Foong" <mfwoo@.yahoo.com> wrote in message
news:B108A0E8-4084-435C-9C6E-815AD808C4AB@.microsoft.com...
> Hi,
> I need a query that can return the total time off between 2 dates.
> I have a table call tblTimeOff which has the following fields
> StartTimeOff, Interval (minute), W
> Sample data for tblTimeOff:-
> 10.00AM, 15, 0 - Timeoff period 10.00am to 10.15am on W
> 12.00pm, 60, 0 - Timeoff period 12.00pm to 1.00pm on W
> 15.00pm,15, 0 - - Timeoff period 3.00pm to 3.15pm on W
> 10.30AM, 15, 1 - Timeoff period 10.30am to 10.45am on W
> 12.30pm, 60, 1 - Timeoff period 12.30pm to 1.30pm on W
> Saturday and Sunday are considered as W
> Mon - Fri are W
> I need a query when user provide me with 2 date:-
> Condition 1:
> --
> Start :- 2nd March 8.30am
> End :- 4th March 11.00am
> The result for total time off should be:- 195 mins
> 2nd March - 15+60+15, 3rd March - 15+60+15, 4th March (w
> Condition 2:
> --
> Start :- 2nd March 8.30am
> End :- 2nd March 5.00pm
> The result for total time off should be:- 90 mins
> 2nd March - 15+60+15
> Anyone help ?
> Thank You,
> mfwoo
>sql
Calculate time lapse
need a store procedure to return the the result recordset which will be
execute from a web page. The database has tables, A and B. For each A
record, there are many related B records. In the B table there is a
timestamp field which tracks the change of A record. For example, A1
has B like the followings:
ID TimeStamp Chg Code Descption
== ========= ======= ========
A1 1138375875 E null //end of the event
A1 1138025002 S resume
A1 1137092615 S don't care
A1 1137092570 S stop
A1 1137092256 I null //start of the
event
I need to generate all records in table A and total elapse time for
each record, but B with Chg Code 'S' that has "don't cacre" to be
deducted from the total time, so that the result will be like this:
ID Name TotalTime
(seconds)
== ==== =======
A1 xyz 351187try this, I haven't tested it:
select A.ID, A.Name, Sum(B.TimeStamp)
from A inner join B on A.ID = B.ID
group by A.ID, A.Name
having (B.ChgCode <> 'S' and B.Description <> 'don''t care')
adi|||js (androidsun@.yahoo.com) writes:
> Can anyone help with the following Transact SQL question? Thanks. I
> need a store procedure to return the the result recordset which will be
> execute from a web page. The database has tables, A and B. For each A
> record, there are many related B records. In the B table there is a
> timestamp field which tracks the change of A record. For example, A1
> has B like the followings:
> ID TimeStamp Chg Code Descption
>== ========= ======= ========
> A1 1138375875 E null //end of the event
> A1 1138025002 S resume
> A1 1137092615 S don't care
> A1 1137092570 S stop
> A1 1137092256 I null //start of the
> event
> I need to generate all records in table A and total elapse time for
> each record, but B with Chg Code 'S' that has "don't cacre" to be
> deducted from the total time, so that the result will be like this:
> ID Name TotalTime
> (seconds)
>== ==== =======
> A1 xyz 351187
It is not clear to how that "don't care" row is to be deducted, since
that is just a point in time. Had you posted CREATE TABLE statements
for the tables, and INSERT statements with the data, it would have been
easy to play around. The below is just a guess, and is untested:
SELECT B.ID, SUM(elapsed)
FROM (SELECT B1.ID, elapsed = B1.TimeStamp - B2.Timestamp,
B2.ChgCode, B2.Description
FROM B B1
JOIN B B2 ON B1.ID = B2.ID
AND B2.TimeStamp = (SELECT MAX(B3.Timestamp)
FROM B B3
WHERE B3.ID = B1.ID
AND B3.TimeStamp <
B1.TimeStamp)
) AS B
WHERE NOT (B.ChgCode = 'S' AND B2.ChgCode = 'don''t care')
GROUP BY B.ID
Here, I'm making the assumption that it is the time from the don't-
care event until the next event that is to be ignored.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks for the reply. The TimeStamp column is the actual time the
event occurs not the length of each event, so summing the column will
not give me the actual length of the time from the start to end. The
calculation should be
(time event starts - time envent ends) - (time resume starts - time
resume stops)
thus the result is
(1138375875 - 1137092256) - (1138025002 - 1137092570) = 351187
Any idea? I think I have to use cursor to loop through each result
block and determine if the Description field contains 'stop' or
'resume'. Thanks.|||Thank you. It works with minor modification. Now I would like to use
a trigger so that upon insert the elapsed time will be posted in Table
A column (int) "TimeLapse". However, it would not accept the value.
Can you help?
ALTER TRIGGER [updateA]
ON [dbo].[B]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
Update A
set A.TimeLapse = (SELECT SUM(elapsed)
FROM (SELECT B1.ID, B1.[TimeStamp] -
B2.[TimeStamp] AS elapsed, B2.ChgCode, B2.description
FROM B B1 INNER JOIN
B B2 ON B1.ID = B2.ID AND
B2.[TimeStamp] =
(SELECT
MAX(B3.Timestamp)
FROM B B3
WHERE B3.ID = B1.ID
AND B3.TimeStamp < B1.TimeStamp)
WHERE not (B1.ChgCode = 'S' and
(b1.description
like '%resume%' or b1.description like '%don''t care%')) OR
(b1.description IS
NULL)) B GROUP BY ID)
END|||js (androidsun@.yahoo.com) writes:
> Thank you. It works with minor modification. Now I would like to use
> a trigger so that upon insert the elapsed time will be posted in Table
> A column (int) "TimeLapse". However, it would not accept the value.
> Can you help?
You must correlate the computation of elapsed with a row in A. The
easiest way is to use the proprietary FROM/JOIN syntax supported by
MS SQL Server:
Update A
set TimeLapse = Btot.elapsed
FROM A
JOIN (SELECT B.ID, elapsed = SUM(elapsed)
FROM (SELECT B1.ID, B1.[TimeStamp] - B2.[TimeStamp] AS elapsed,
B2.ChgCode, B2.description
FROM B B1
JOIN B B2 ON B1.ID = B2.ID
AND B2.[TimeStamp] =
(SELECT MAX(B3.Timestamp)
FROM B B3
WHERE B3.ID = B1.ID
AND B3.TimeStamp < B1.TimeStamp)
WHERE not (B1.ChgCode = 'S' and
(b1.description like '%resume%' or
b1.description like '%don''t care%'))
OR (b1.description IS NULL)) B
GROUP BY B.ID) AS Btot = A.ID = B.ID
However, neither this is entierly satisfactory, as you are reading the
entire B table a couple of times on each insert, and this could be
expensive. SQL Server offers the the virtual tables "inserted" and
"deleted" which holds after-image and before-images of the rows
affected by the statement. (For an INSERT, there are only rows in
"inserted" obviously.)
Rewriting the trigger to look at inserted is not trivial, least of all
if rows can be inserted out of order. (What if a "don't care" row is
inserted in the middle of it all?)
Not knowing the exact scenario where this appears I prefer to not suggest
a solution.
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
Calculate Time difference
I have a table GPSDATA which consists of
VehicleNo,Speed,CurrentDate,slno,status
This data gets updated every minute.And every minute the slno(serial no) will be incremented automatically.
The status field shows whether the vehicle is moving or idle(That is neither in stop nor in moving) position
The user will choose the vehicleno(From the Front End which is VB.net 2005)
and I want to display the time difference between the current time and the latest time of the vehicle.
I will check that if the status is in idle and the time difference is more than 30 minutes then make the status as stop.
Kindly let me know how to frame this query.
Thanks
cmrhema
Quote:
Originally Posted by cmrhema
Hello
I have a table GPSDATA which consists of
VehicleNo,Speed,CurrentDate,slno,status
This data gets updated every minute.And every minute the slno(serial no) will be incremented automatically.
The status field shows whether the vehicle is moving or idle(That is neither in stop nor in moving) position
The user will choose the vehicleno(From the Front End which is VB.net 2005)
and I want to display the time difference between the current time and the latest time of the vehicle.
I will check that if the status is in idle and the time difference is more than 30 minutes then make the status as stop.
Kindly let me know how to frame this query.
Thanks
cmrhema
Get the latest date of the vehicle using:
SELECT TOP 1
@.slno = slno,
@.lastDate = CurrentDate
FROM YourTable
WHERE VehicleNo = @.vehicleno
ORDER BY CurrentDate DESC
Then compare the dates of the records using:
IF DATEDIFF(minute, @.lastDate, GETDATE()) > 30 BEGIN
UPDATE YourTable
SET status = 'stop'
WHERE slno = @.slno
END|||
Quote:
Originally Posted by DonlonP
Get the latest date of the vehicle using:
SELECT TOP 1
@.slno = slno,
@.lastDate = CurrentDate
FROM YourTable
WHERE VehicleNo = @.vehicleno
ORDER BY CurrentDate DESC
Then compare the dates of the records using:
IF DATEDIFF(minute, @.lastDate, GETDATE()) > 30 BEGIN
UPDATE YourTable
SET status = 'stop'
WHERE slno = @.slno
END
Thanks solved the problem
Tuesday, March 20, 2012
Calculate Time between pairs of records (TimeTicket)
Job, EventType,TimeEvent
A,Start,12/10/2005 10:00
A,End, 12/10/2005 10:30
B,Start, 12/10/2005 10:31
B,End, 12/10/2005 11:45
and so on...
Which is the way to have a quey result with
Job, JobTime (in minutes)
A, 30
B, 74
ThanksDamiano wrote:
> I have a table like this
> Job, EventType,TimeEvent
> A,Start,12/10/2005 10:00
> A,End, 12/10/2005 10:30
> B,Start, 12/10/2005 10:31
> B,End, 12/10/2005 11:45
> and so on...
> Which is the way to have a quey result with
> Job, JobTime (in minutes)
> A, 30
> B, 74
> Thanks
SELECT Job, DATEDIFF(mi, MIN(TimeEvent), MAX(TimeEvent)) AS Jobtime
FROM table
GROUP BY Job
This needs to have the Job completed for "usable" results.
HTH,
Pierre
/"\ ASCII Ribbon Campaign
\ /
X Against HTML
/ \ in e-mail & news|||"Pierre Albisser" wrote:
> SELECT Job, DATEDIFF(mi, MIN(TimeEvent), MAX(TimeEvent)) AS Jobtime
> FROM table
> GROUP BY Job
> This needs to have the Job completed for "usable" results.
> --
> HTH,
> Pierre
> /"\ ASCII Ribbon Campaign
> \ /
> X Against HTML
> / \ in e-mail & news
>
Thanks, this was usefull
but now I have some more diffucult (for me)
The table (TimeTicket) now is like this:
Job,Operator,EventType,EndOperationType,
TimeEvent
A;X;Start;null;12/10/2005 10:00
A;X;End;OperType1;12/10/2005 10:30
A;X;Start;null;12/10/2005 10:31
A;X;End;OperType1;12/10/2005 11:45
A;Y;Start;null;12/10/2005 13:00
A;Y;End;OperType2;12/10/2005 14:00
B;X;Start;null;12/10/2005 13:00
B;X;End;OperType2;12/10/2005 13:15
table is sort by Job,Operator,TimeEvent
the result should be
Job;Operator;EndOperationType;JobTime
A;X;OperType1;30
A;X;OperType1;76
A;Y;OperType2;60
B;X;OperType2;15
I think in this case is necessary to parse the table row by row,
to take the start time from the first,
and the oder data from the second,
calculate the time and the fields to ouput.
Probably I need a function
select * from CalculateTimeTicket()
Thanks again.|||First, get your start and end dates...
select job,
operator,
eventtype,
operatortype,
starttime = timeevent,
endtime = ( select top 1 timeevent
from timeticket te
where te.job = t.job
and te.operator = t.operator
and te.operatortype = t.operatortype
and te.eventtype = 'End'
and te.timeevent > t.timeevent
)
from timeticket t
where eventtype = 'start'
then you can do a datediff...
select job,
operator,
operatortype
jobtime = datediff( minute, starttime, endtime )
from (
select job,
operator,
starttime = timeevent,
endtime = ( select top 1 timeevent
from timeticket te
where te.job = t.job
and te.operator = t.operator
and te.eventtype = 'End'
and te.timeevent > t.timeevent
)
from timeticket t
where eventtype = 'start' ) as d
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Damiano" <Damiano@.discussions.microsoft.com> wrote in message
news:AC8308CB-D424-4387-B04C-15DC8DA515DB@.microsoft.com...
> "Pierre Albisser" wrote:
>
> Thanks, this was usefull
> but now I have some more diffucult (for me)
> The table (TimeTicket) now is like this:
> Job,Operator,EventType,EndOperationType,
TimeEvent
> A;X;Start;null;12/10/2005 10:00
> A;X;End;OperType1;12/10/2005 10:30
> A;X;Start;null;12/10/2005 10:31
> A;X;End;OperType1;12/10/2005 11:45
> A;Y;Start;null;12/10/2005 13:00
> A;Y;End;OperType2;12/10/2005 14:00
> B;X;Start;null;12/10/2005 13:00
> B;X;End;OperType2;12/10/2005 13:15
> table is sort by Job,Operator,TimeEvent
> the result should be
> Job;Operator;EndOperationType;JobTime
> A;X;OperType1;30
> A;X;OperType1;76
> A;Y;OperType2;60
> B;X;OperType2;15
> I think in this case is necessary to parse the table row by row,
> to take the start time from the first,
> and the oder data from the second,
> calculate the time and the fields to ouput.
> Probably I need a function
> select * from CalculateTimeTicket()
> Thanks again.|||Hi Damiano,
how about this one:
SELECT Job, Operator, MAX(EventType) AS EventType, DATEDIFF(mi,
MIN(TimeEvent), MAX(TimeEvent)) AS Jobtime
FROM table
GROUP BY Job, Operator
This should do, as 'Operator' > null (as any value which is not null
would).
HTH,
Pierre
/"\ ASCII Ribbon Campaign
\ /
X Against HTML
/ \ in e-mail & news
Calculate The Time To Run SP
There is Any Way To Calculate The Time To Run SP Or Select Statement Before
Run It
For Example
SELECT *
FROM stores
WHERE (state = 'CA')
How long Time Take This Query to Run
Thankstry using
SET STATISTICS TIME ON|||No, there are no such facilities in SQL Server. One of the reasons is that t
he optimize can pick
different executing plans, and any estimates based on one execution plan wil
l be totally off if some
other execution plan is selected. You also have the probability of blocking.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Taha" <taha105@.hotmail.com> wrote in message news:efD9epuVGHA.5364@.tk2msftngp13.phx.gbl...
> Hi All
> There is Any Way To Calculate The Time To Run SP Or Select Statement Befor
e Run It
> For Example
> SELECT *
> FROM stores
> WHERE (state = 'CA')
> How long Time Take This Query to Run
> Thanks
>|||Thank You Fro Reply
But What I Looking For UDF Or SP That Return Elapsed time For Select
Statement I Send To This SP Or UDF Whit out Run it Men Not Need Data Return
Just The Time To Calculate This Statement
Because I Have Large data and I want say to the user how many this query
take time
Thanks
"Taha" <taha105@.hotmail.com> wrote in message
news:efD9epuVGHA.5364@.tk2msftngp13.phx.gbl...
> Hi All
> There is Any Way To Calculate The Time To Run SP Or Select Statement
> Before Run It
> For Example
> SELECT *
> FROM stores
> WHERE (state = 'CA')
> How long Time Take This Query to Run
> Thanks
>|||As a maximum you could say them an approximation
--
Please post DDL, DCL and DML statements as well as any error message in
order to understand better your request. It''s hard to provide information
without seeing the code. location: Alicante (ES)
"Taha" wrote:
> Thank You Fro Reply
> But What I Looking For UDF Or SP That Return Elapsed time For Select
> Statement I Send To This SP Or UDF Whit out Run it Men Not Need Data Retur
n
> Just The Time To Calculate This Statement
> Because I Have Large data and I want say to the user how many this query
> take time
> Thanks
>
> "Taha" <taha105@.hotmail.com> wrote in message
> news:efD9epuVGHA.5364@.tk2msftngp13.phx.gbl...
>
>|||There is no way to find an accurate time for an SP to run. As Tibor Karaszi
had said, the same SP can run for different periods depending on the server
load, configuration, database size and the mood of the SQL Engine :)
You can only find the time it took for the current execution.|||Ok How find the time it took for the current execution Please
Only Time return Parameter I need
Thanks
"Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
news:8BA9246F-EC38-491C-B1B6-E7B9B3ADE53D@.microsoft.com...
> There is no way to find an accurate time for an SP to run. As Tibor
> Karaszi
> had said, the same SP can run for different periods depending on the
> server
> load, configuration, database size and the mood of the SQL Engine :)
> You can only find the time it took for the current execution.
>|||You have to do this yourself. Either in the client application (declare a va
riable, set it to
current time before execution and after execution check number of ms or s el
apsed), or in the stored
procedure with same basic logic and have an output parm of the procedure whe
re you send out the
number of ms.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Taha" <taha105@.hotmail.com> wrote in message news:eRATWOxVGHA.440@.TK2MSFTNGP10.phx.gbl...[
color=darkred]
> Ok How find the time it took for the current execution Please
> Only Time return Parameter I need
> Thanks
> "Omnibuzz" <Omnibuzz@.discussions.microsoft.com> wrote in message
> news:8BA9246F-EC38-491C-B1B6-E7B9B3ADE53D@.microsoft.com...
>[/color]|||Thanks
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:OguNqexVGHA.1536@.TK2MSFTNGP15.phx.gbl...
> You have to do this yourself. Either in the client application (declare a
> variable, set it to current time before execution and after execution
> check number of ms or s elapsed), or in the stored procedure with same
> basic logic and have an output parm of the procedure where you send out
> the number of ms.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> Blog: http://solidqualitylearning.com/blogs/tibor/
>
> "Taha" <taha105@.hotmail.com> wrote in message
> news:eRATWOxVGHA.440@.TK2MSFTNGP10.phx.gbl...
>|||You can use profiler also.
Regards
Amish shahsql
Calculate integral of time series
I want to compute an integral of values in a table that has 2 columns:
Column A: Time-stamp (T)
Column B: value (KWH)
I need to compute the sum of (KWH*(T(n)-T(n-1)))
Could you suggest a way to do it in T-SQL?
thanks
AmiAmi Einav wrote:
>I need to compute the sum of (KWH*(T(n)-T(n-1)))
Ad an autoincrementing id to your Table named idTbl
Assuming Tbl as Your Tablename
SELECT Tbl.T, Tbl2.T, Tbl.KWH , Tbl.KWH*(Tbl.T-Tbl2.T) as KWHt
FROM Tbl
INNER JOIN Tbl as Tbl2 on Tbl2.idTbl+1 = Tbl.idTbl
Maybe you a datetime - conversion to get the calculation work.
in the step Goup/Sum it together as you like
greetings,
J.C.|||Thanks Joe - that's exactly what I was looking for.
Ami
"Joe Care" <u18810@.uwe> wrote in message news:5c0163d5b2f02@.uwe...
> Ami Einav wrote:
> Ad an autoincrementing id to your Table named idTbl
> Assuming Tbl as Your Tablename
> SELECT Tbl.T, Tbl2.T, Tbl.KWH , Tbl.KWH*(Tbl.T-Tbl2.T) as KWHt
> FROM Tbl
> INNER JOIN Tbl as Tbl2 on Tbl2.idTbl+1 = Tbl.idTbl
> Maybe you a datetime - conversion to get the calculation work.
> in the step Goup/Sum it together as you like
> greetings,
> J.C.sql