Showing posts with label calculated. Show all posts
Showing posts with label calculated. Show all posts

Thursday, March 8, 2012

Calling .Net assemblies (AS SProcs) from Calculated Measure MDX

Hi,

Okay I am desperately stuck again. This topic gives a lot of search results but none seem to help me. I have a .Net assembly (class library) that I have registered in Analysis Server 2005. I can now see it in the Assemblies Folder of SSAS.

I want to call a method in this assembly in the MDX expression of a calculated measure in my cube!

Is this possible?

I checked this article from microsoft:

http://msdn2.microsoft.com/en-us/library/ms176113.aspx

but it does not work. It gives me an error saying that the function does not exists.

Please do guide me or give me steps to do the same. If this is not possible how else can i compliement .NET functions in my calculted measure's MDX expression.

Regards

Vijay R

Hi Vijay,

The source code for the Analysis Services Stored Procedure project includes a complete set of MDX queries showing how to call sprocs:

http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=ASStoredProcedures

So it is possible to do what you want to do!

HTH,

Chris

Wednesday, March 7, 2012

Call function from a procedure and assign return value to variable (sql server)

Hi all,
I have a procedure proc1, which needs to update a table.
One of the columns to update the table is calculated using a function
funct1 (which returns a smalldatetime)
My problem is how do I call the function funct1 from procedure proc1,
so that the return value of function is saved in a variable in
procedure.
Sample Procedure Proc1
ALTER PROCEDURE proc1
@.x int
AS
declare @.ret smalldatetime
--Here, I want @.ret to be a smalldatetime value returned by function
funct1.
--I tried the below (though knowing it wont work):
--@.ret = select dbo.funct1(param1), but it gives error.
--I even tried(again, though knowing it wont work):
--update myTable set field1 = select dbo.funct1(param1), but it gives
error.
--WHERE ...
update myTable set field1 = @.ret
WHERE ...
Sample function funct1:
alter FUNCTION dbo.funct1
(
@.val1 decimal,
@.val2 int
)
RETURNS smalldatetime
AS
BEGIN
DECLARE @.ret1 decimal
DECLARE @.ret2 smalldatetime
DECLARE sel_Cursor CURSOR FOR SELECT field1, field2
FROM myTable
OPEN sel_Cursor
FETCH NEXT FROM sel_Cursor INTO @.ret1, @.ret2
CLOSE sel_Cursor
DEALLOCATE sel_Cursor
if @.val1 = @.ret2
return @.ret2
else
set @.ret2 = some function...
RETURN @.ret2
END
---
Pls help..
TIA..Whats the error ? Normally you could use it by using this sample query
SELECT @.ret = dbo.SomeFunction(@.SomeParam)
HTH, Jens Suessmeyer.|||Thanks guys..
Damn, I dont knw why i was using the 'select'. Now it worked for me.
Trey,
I am using the cursor to fetch value and assign it to a variable.
The 'where' clause fetches single row.
And the select query returns single value.
But still i have used cursor coz thts the only way I know (I am pretty
new to SQL :( ).
Is there any other way to do so'
Trey Walpole wrote:
> What is that cursor supposed to be doing?
> Are you really looping through the whole table to get a single value'
> And possibly some random value at that?
> i cannot in good conscience give you an answer and let you keep that UDF..
.
>
> Chris wrote:|||Chris wrote:
> Hi all,
> I have a procedure proc1, which needs to update a table.
> One of the columns to update the table is calculated using a function
> funct1 (which returns a smalldatetime)
> My problem is how do I call the function funct1 from procedure proc1,
> so that the return value of function is saved in a variable in
> procedure.
>
> Sample Procedure Proc1
> ALTER PROCEDURE proc1
> @.x int
> AS
> declare @.ret smalldatetime
> --Here, I want @.ret to be a smalldatetime value returned by function
> funct1.
> --I tried the below (though knowing it wont work):
> --@.ret = select dbo.funct1(param1), but it gives error.
> --I even tried(again, though knowing it wont work):
> --update myTable set field1 = select dbo.funct1(param1), but it gives
> error.
> --WHERE ...
> update myTable set field1 = @.ret
> WHERE ...
>
> Sample function funct1:
> alter FUNCTION dbo.funct1
> (
> @.val1 decimal,
> @.val2 int
> )
> RETURNS smalldatetime
> AS
> BEGIN
> DECLARE @.ret1 decimal
> DECLARE @.ret2 smalldatetime
> DECLARE sel_Cursor CURSOR FOR SELECT field1, field2
> FROM myTable
> OPEN sel_Cursor
> FETCH NEXT FROM sel_Cursor INTO @.ret1, @.ret2
> CLOSE sel_Cursor
> DEALLOCATE sel_Cursor
> if @.val1 = @.ret2
> return @.ret2
> else
> set @.ret2 = some function...
> RETURN @.ret2
> END
> ---
> Pls help..
> TIA..
Why does the function use a cursor? Why don't you just assign the
result of the function to a variable?
Please post DDL, sample data and required results as described in:
http://www.aspfaq.com/etiquette.asp?id=5006
David Portas
SQL Server MVP
--|||Chris wrote:
> Thanks guys..
> Damn, I dont knw why i was using the 'select'. Now it worked for me.
> Trey,
> I am using the cursor to fetch value and assign it to a variable.
> The 'where' clause fetches single row.
> And the select query returns single value.
> But still i have used cursor coz thts the only way I know (I am pretty
> new to SQL :( ).
> Is there any other way to do so'
>
In that case you probably don't need the cursor or the function. You
can do it in the UPDATE. For example:
UPDATE your_table
SET col =
(SELECT col
FROM other_table
WHERE ...)
WHERE ...
etc.
Set-based code should be your first choice for this kind of thing. If
you are new to SQL then you shouldn't be using cursors AT ALL. You can
do a lot of damage that way.
David Portas
SQL Server MVP
--|||Hey david,
In the function, I am doing calculation with two different tables, and
the value returned is compared with the parameter i am passing in the
function.
If the values are same, I am not supposed to change the value in
tables.
If its different, some calculations are made, and the new value is
inserted.
For this, I am using cursor, because I need to save value to a variable
to compare, as well as calculate.|||Chris wrote:
> Hey david,
> In the function, I am doing calculation with two different tables, and
> the value returned is compared with the parameter i am passing in the
> function.
> If the values are same, I am not supposed to change the value in
> tables.
> If its different, some calculations are made, and the new value is
> inserted.
> For this, I am using cursor, because I need to save value to a variable
> to compare, as well as calculate.
A) You don't need to use a cursor to assign a value to a variable. You
can use SET
SET @.var =
(SELECT col
FROM your_table
WHERE ...)
For multiple assignment you can use SELECT:
SELECT @.col1 = col1, @.col2 = col2
FROM your_table
WHERE ...
B) You don't need a function to do all the joins and calculations you
talked about. You should be able to do that in an UPDATE statement in
almost every case. Most cases, doing it in the UPDATE statement will
perform better than using a function.
Unfortunately you didn't give us enough information to reply with
alternative solutions. That's why the convention is to post DDL, sample
data, and your required end results. I posted a link earlier that
explained how to do that.
Let me explain why I said you shouldn't use cursors. I didn't meant
that as serious advice rather than a rebuke. The reason is that most of
the time cursors are a bad choice for solving problems in SQL. Those
who don't know SQL well tend to write over-complex, inefficient and
buggy cursor code. Only when you know SQL really well will you have the
experience to know when a cursor is a sensible idea. Until then it
really is safest to avoid them altogether.
Hope this helps.
David Portas
SQL Server MVP
--|||Thanx for the help Dave,
I will try doing it this way..

call custom SQL function in ASP.NET

I made an SQL function in MSSQL2000. This is a function that get's a calculated heat emission. When I run the Query in MSSQL2000 the function works. It calculates every emission for every row. When I call this SQL function in VS2005, it says it does not recognize the function. Does anyone know what this may cause? thank you. For the people who are bored, I added the SQL statement. The error is at the function

SELECT TOP 15 tbProducts.prod_code, tbProductProperties.prop_height, tbProductProperties.prop_length, tbProductProperties.prop_type, tbProductProperties.prop_default_emission, tbProductProperties.prop_weight, tbProductProperties.prop_water_volume, tbProductProperties.prop_n_value, GetHeatEmission(50,70,20,[prop_default_emission],[prop_n_value]) AS customEmission FROM tbProductClassification INNER JOIN tbProducts ON tbProductClassification.clprod_fk_prod_id = tbProducts.prod_id INNER JOIN tbProductProperties ON tbProducts.prod_id = tbProductProperties.prop_fk_prod_id WHERE (tbProductClassification.clprod_fk_class_id = 3327) AND (prop_height >= '030') AND (prop_height = '060') AND (prop_lengthYou may try to use the full name of that function, like dbo.GetHeatEmission().

Friday, February 24, 2012

Calculations Script Order and Formatting

I have a parent-child dimension for Accounts with a calculated member drapped off of the top level that figures Net Earnings % using a measure called Amount. As described by the name of the member, I need this expressed as a percentage. I am using this calc in the same view as a (Shell/Utility) Time Calculations dim that figures Year-to-date, Prior Year-to-date, YTD % Change, etc.... Depending on the order of the calculations in the calculations script I get different results. If I put the formula for the Net Earnings % before the MDX for the Time Calculations the results comes out correct but the formating gets overidden by the formating applied when the Time Calulations are applied. So the Net Earnings % for [YTD] and [YTD PY] are expressed as decimals and [YTD % Change] is expressed as a percentage. If I flip the order in the calculations script the formating gets corrected because the formatting of the Net Earnings % get applied last but my results for Net Earnings % are incorrect for [YTD % Change] because they were applied after the Time Calculations and end up applying the formula using the reults (the percentages) of the [YTD % Change] calc instead of the numbers used to make up that percentage.

Is there a way to put the Net Earnings % MDX before the Time Calculations MDX so that the results are correct for [YTD % Change] and reapply the formating of percent to [YTD] and [YTD PY] after the formatting of the Time Calculations get applied?

Nevermind, I figured it out. I placed the Net Earnings % MDX before the Time Calculations MDX and placed the following MDX after the Time Calculations MDX:

Code Snippet

Scope({[Account].[Account Hierarchy].[Net Earnings%]});

FORMAT_STRING(THIS) = "Percent";

End Scope;

|||

Nevermind, I figured it out. I placed the Net Earnings % MDX before the Time Calculations MDX and placed the following MDX after the Time Calculations MDX:

Code Snippet

Scope({[Account].[Account Hierarchy].[Net Earnings%]});

FORMAT_STRING(THIS) = "Percent";

End Scope;

Calculations Question

Hello,

Is there a way to make a Calculated Member aggregatable? I want to create a Calculated Member that performs a certain formula at the leaf level only. On the upper levels of the hierarchy I want the value aggregated, not the formula re-applied. Is there a way to achieve this?

Another question, is there a way to apply a special formula for a measure? and what is the "MeasureExpression" Property of a measure to be used for?

Thanks

For the first part:

You could create real measure that has all values as NULL. This will not take any space in database. Then you assign calculations in your calculated area and this measure will behave like real measure. This is based on Mosha Pasumansky suggestion here:

http://sqljunkies.com/WebLog/mosha/archive/2006/11/16/sqlpass_udm_presentation.aspx

Quote:

6. It isn't a problem that calculated measures don't aggregate up. If the designer need to add calculated measure which has aggregation semantics of a real measure, than there is very simple way to do it. Add a real measure to the measure group, and specify NULL as its column binding. It will cost nothing during processing, the partition size is going to be exactly the same, because AS will easily detect that measure value is constant and will compress it to 0 bits. But then in MDX Script, when expressions are assigned to that measure - they will aggregate up using measure's aggregation function - and it should work very efficiently too.

Some info about "MeasureExpression" property can be found in this thread: http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=768757&SiteID=17

Vidas Matelis

Calculations across semi-related fact tables

Using the AdventureWorks database as an example:

If I create a calculated measure that is the sum of total sales across InternetSales and ResellerSales, how do I ensure that when I am browsing the cube, that my total sales value is always accurate even when I filter the cube on a dimension that applies to one fact table, but not the other.

For example, if I am browsing the cube by Sales Territory and I apply a filter on a specific Reseller Type (for instance Warehouse), then I would expect that for Sales Territories that did not have ResellerSales with a Reseller Type of Warehouse, the value displayed for Total Sales would be blank.

However, because the non-empty behavior for the calculation is the combination of InternetSales and Reseller Sales, the InternetSales value will always be displayed (even though it does not make sense based on the filter).

Is there a way to change this behavior?

I ran the following query against an unmodified version of the Adventure Works DW database:

Code Snippet

with member [Measures].[x] as

[Measures].[Reseller Sales Amount] +

[Measures].[Internet Sales Amount]

select

{

[Measures].[Reseller Sales Amount],

[Measures].[Internet Sales Amount],

[Measures].[x]

} on 0,

Geography.Country.Members on 1

from [Adventure Works];

At the All Geographies member of the Country attribute hierarchy, Internet Sales Amount had a value of $29M. Against individual countries, this same $29M figure was repeated as the Internet Sales measure group has no relationship with this dimension. If you think about how SSAS handles cube space definition, this makes sense even though it is counter-intuitive to most users.

Then, the question is how is the calculated member [x] handled? The $29M is added to whatever value for Reseller Sales Amount is returned.

I then went into the cube designer in BIDS for the Adventure Works cube, selected the Internet Sales measure group, and then pulled up its properties. I set IgnoreUnrelatedDimensions to False and reprocessed the cube. When I executed the query again, I got the same $29M for the All Geographies member, but NULL for its children. The calculated member [x] reflected $29M + Reseller Sales Amount for the All Geographies member and just Reseller Sales Amount for the other members.

Bryan

Sunday, February 19, 2012

calculation problem

Hello,

We have time dimension (month, week)

and fact table, total_revenue, no_of_work_day, order, order type....

We added a calculated member : Ave revenue/work_day
Expression: "[Measures].[Tot Revenue]/[Measures].[No Of Work Day]"
in BI studio, but result is wrong.

Something wrong with 'no_of_work_day' , but how to correct it?

Thank you very much for any help.

In spite of using calculated member inside cube, try to create a named calculation inside datasourceview!?

In the table of datasourceview, right-click and add a named calculation a insert your formula TotRevenue/NoOfWorkDay...

Regards!

|||

Can you show us your mdx query?

You try using the SUM(...) function on the measures members and dividing with it...

I would also like to say that you can create your calculated member in the cube...


Regards,

|||Thank you very much PedroCGD and Luis for the advice,

I tried using named calculation, it works. Great!

What is different between named calculation and calculate command inside cube?

I really appreciated your help.
|||

Dear Olap_user,

Always try to use named calculations... only when you need to calculate inside aggregations you use calculated member. The big advantage of using named calculation is that the system spend time to do calculates only once, and with calculated member each time you query the cube. So:

Named Calculation > each time your process cube

Calculated member > each time you query the cube!

Helped you?

Regards!!!

|||Thank you very much for the detail explanation, using Named Calculation is better for the performance.

Your explanation is very helpful.

Thanks a lot.

Tuesday, February 14, 2012

Calculating Luhn Digit in Crystal Reports

I have an 18 digit number and i need a SQL formula in Crystal Reports to calculate the Luhn digit.

Below is how Luhn is calculated.

Step 1: Double the value of alternate digits beginning with the first right hand digit.

e.g 8 6 3 7 5 = 8 12 3 14 5

Step 2: Add the individual digits compromising the products obtained in Step 1 to each of the unaffected digits in the original number.

e.g 8 12 3 14 5 = 8+1+2+3+1+4+5 (total=24)

Step 3: Subtract the total obtained in Step 2 from the next higher number ending in 0.

e.g 24 = 30-24 = 6 (Luhn = 6!)

Any help here would be fantastic!!This should do it...

Local StringVar sValue := {test.NUMBER};

Local NumberVar nSubtotal;
Local NumberVar i;

For i := (Length(sValue) - 1) To 1 Step -2 Do
(nSubtotal := nSubtotal + CDbl(sValue[i]));

For i := Length(sValue) To 1 Step -2 Do
nSubtotal := nSubTotal + (If CDbl(sValue[i]) < 5
Then CDbl(sValue[i]) * 2
Else
CDbl(sValue[i]) - (9 - CDbl(sValue[i])));

nSubtotal Mod 10;

Sunday, February 12, 2012

Calculating grand total in header

I have a report that has a Page Total and a Grand Total in the header.
The Page Total is being calculated from a field in the report like so:
=sum(ReportItems!tcBodyAmount.Value)
where tcBodyAmount is the name I gave the textbox in the report body
that calculates a value.
However, now I need a Grand Total and I can't get the syntax correct.
I've tried summing the PageTotal and I get a different error each time.
I can't use a field in the header. I tried doing a sum on the Page
Total sum but get the error that aggregate functions can't be nested.
I've also tried moving the totals into the body of the report and I get
the error that aggregate functions can only be used in the header and
footer.
The help feature was never loaded so I don't have access to that. Can
anyone give me some guidance on this? Thank you!try a sub report that calcs the total and thats in your header|||I tried that and got a message saying that a subreport can't be placed
in the header or footer|||Try placing in the header
= sum(Fields!Fieldname.Value,"datasetname")
see if that works
--
Wayne Snyder MCDBA, SQL Server MVP
Mariner, Charlotte, NC
I support the Professional Association for SQL Server ( PASS) and it''s
community of SQL Professionals.
"Carol" wrote:
> I have a report that has a Page Total and a Grand Total in the header.
> The Page Total is being calculated from a field in the report like so:
> =sum(ReportItems!tcBodyAmount.Value)
> where tcBodyAmount is the name I gave the textbox in the report body
> that calculates a value.
> However, now I need a Grand Total and I can't get the syntax correct.
> I've tried summing the PageTotal and I get a different error each time.
> I can't use a field in the header. I tried doing a sum on the Page
> Total sum but get the error that aggregate functions can't be nested.
> I've also tried moving the totals into the body of the report and I get
> the error that aggregate functions can only be used in the header and
> footer.
> The help feature was never loaded so I don't have access to that. Can
> anyone give me some guidance on this? Thank you!
>|||I had tried exactly that and I get the error message that fields cannot
be called in the header. I even did a search on that one and found an
old posting that said that cannot be done.
I tried the Grand Total as =sum(ReportItems!PageTotal.Value), thinking
that should sum all of the page totals. I didn't get an error, but
instead got no output for both the Grand Total and the Page Total when
I did that. Weird because when I clear that sum, the Page Total prints
fine.

Friday, February 10, 2012

Calculated/derived measures

Hello again.

I'm wondering if it's possible to add some form of calculated field to my fact table.

Scenario... I have a fact table that records customer account balances a the end of each day. As this is a bank we're talking about, some of the balances are in credit & some overdrawn.

Since the AccountBalance field aggregates by default to sum, if for example I wish to view balances by product I get the NET balances (i.e. all debit & credit balances summed). This is OK, however obviously my people will want to be able to split these in to

Credit Balances

Product

a 100

b 100

c 100

Debit Balances

Product

a -50

b -50

c -50

as opposed to the current situation where I get

Balances

Product

a 50

b 50

c 50

Hope this is clear... question is... how do I go about it ? Calculated field, derived field... I tried a simple IIF calculation but the trouble is it went something like

IIF([measures].[FactAccountBals] >=0, [measures].[FactAccountBals] ,0)

to give me credit balances, however (as you can imagine) it returns ZERO for all debit balance accounts, whereas I want to ignore them... but how ?

You can make another column in your fact table that is either "Credit" or "Debit" and then make an attribute out of that.

Then you can add that attribute to your mdx statement and have items broken out by transaction type.

|||Sorry, stupid question, but how do I make an attribute out of a fact table field record ?|||

OK for anyone else here's what I ended up doing.

Created a New Dimension called Dim Baltype with just 2 records, Debit Bal & Credit Bal

Then ran an update query on the fact table where I added and extra field to signify Dr or Cr balance & linked that to Dim Baltype - This now enables me to split by Loans and deposits in the cube.

Thanks for the steer

Calculated values and database design.

Hi everybody,

I need some help on calculated values in my database design.

I'm creating an accounting / business management application with the
usual modules like A/R, A/P, Inventory, etc.

I don't know how to handle calculated values in fields like "Customer
Balance", "Inventory Item Qty on Hand", "Inventory Item Qty Last cost"
and other similar.

I don't want to create fields in the database to store these values
but I want to create them on the fly instead. Another thing I prefer
to do is use code in my application (vb.net) not T-SQL to do this
(stored procedure or views), because this way I'm moving business
logic into SQL; so far all the logic is located in a Business Rules
DLL.

My question is how can I do that and at the same time achieve "easy"
joins.

For example:
Every time I retrieve some customer's info I need his balance. Let's
say if my query is:

SELECT CustomerID, CustomerName, Address from Customers
Where CustomerID = xxxxxx'

How can I retrieve the balance, when is calculated from other fields
in other tables, such as Invoices, Credit Memos and Cash Receipts?

I thought to use views and add a join to the above query. Is that good
or bad, performance wise?

What other options I have?

Looking forward for your answer.

Thanks in advanced.
StefanosBusiness logic belongs server-side if it involves summarizing data.
Otherwise you might as well use a file-server database like Access. You
don't want to have to retrieve all the data just to add it up at the client.

I can only guess at your table structure and keys but maybe this example
will help:

SELECT C.customerid, C.customername, C.address,
SUM(T.trans_amount) AS balance
FROM Customers AS C
JOIN Transactions AS T
ON C.customerid = T.customerid
AND C.customerID = 'xxxxxx'

--
David Portas
SQL Server MVP
--|||OOPS! That wasn't very good!

Correction:

SELECT C.customerid, C.customername, C.address,
SUM(T.trans_amount) AS balance
FROM Customers AS C
JOIN Transactions AS T
ON C.customerid = T.customerid
AND C.customerID = 'xxxxxx'
GROUP BY C.customerid, C.customername, C.address

--
David Portas
SQL Server MVP
--|||David,

Thanks for your reply.

I'm following a "fat-client" implementation.
I agree that business rules belong to the server or in my case the
"fat client".
I don't want to put any logic on the database in the form of sprocs or
similar;
I have enough layers in my design already and I don't want to be tied
in a particular RDBS (currently using MS SQL 2000).

A query like the one you posted is what I've thinking to do, but I
hoped maybe someone has a better solution.
Queries like these are very hard to create in multiple joins.

In your example the table "Transactions" isn't enough.

I have to get totals from:
* InvoiceHeader
* CreaditMemoHeader
* CashReceiptsHeader

Imagine now if I have to get the balance in a query that has another
2-3 joins on it.

Stefanos

"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message news:<OpidnUri8Z4fmRndRVn-sQ@.giganews.com>...
> OOPS! That wasn't very good!
> Correction:
> SELECT C.customerid, C.customername, C.address,
> SUM(T.trans_amount) AS balance
> FROM Customers AS C
> JOIN Transactions AS T
> ON C.customerid = T.customerid
> AND C.customerID = 'xxxxxx'
> GROUP BY C.customerid, C.customername, C.address

calculated value based on values in other row

hello,
in a table i have 3 fields
custnr wnr profit
example
1 1 100
1 2 110
1 3 120
1 4 150
i want to calculate how much the profit grows referenced from wnr 1 and
the relative to the precedent w
1 1 0% 0%
1 2 10% 10%
1 3 20% 10%
1 4 50% 30%
thanksXavier wrote:

> i want to calculate how much the profit grows referenced from wnr
> 1 and the relative to the precedent w
> 1 1 0% 0%
> 1 2 10% 10%
> 1 3 20% 10%
> 1 4 50% 30%
This should work:
select profit/ (select top 1 TB2.profit from table TB2 where TB2.wnr
< TB1.wnr order by wnr DESC) from table TB1
HTH,
Stijn Verrept.|||thanks for your help,
in the table there are a lot of custnr.
The corect form of the example table is analog to the custNr 1 there are
also Nr like
custnr wnr profit
example
1 1 100
1 2 110
1 3 120
1 4 150
2 1 100
2 2 120
2 3 140
2 4 160
3 1 100
3 2 120
3 3 130
3 4 140
...
how can i extend to have a corect calculation for all customer
best regards
"Stijn Verrept" wrote:

> Xavier wrote:
>
>
> This should work:
> select profit/ (select top 1 TB2.profit from table TB2 where TB2.wnr
> < TB1.wnr order by wnr DESC) from table TB1
> --
> HTH,
> Stijn Verrept.
>|||Xavier wrote:

> ...
> how can i extend to have a corect calculation for all customer
select profit/ (select top 1 TB2.profit from table TB2 where TB2.wnr
< TB1.wnr and TB2.custnr
= TB1.custnr order by wnr DESC) from table TB1
HTH,
Stijn Verrept.|||yes, it works, thanks
best regards
Xavier

calculated valu

hello,
in a table with 2 fields (department and sales) i have to calculate the
sales for the company and the sales excluded spme departments.
example original table
OnlyDepA 100
OnlyDepB 200
OnlyDepC 500
.........
AllDep. 10000
What i need to calculate
What are the sales forAllDep without the sales for (OnlyDepA or ...)
example how the calculation is made,
AllDep. -OnlyDepA =10000 -100=9900
AllDep. -OnlyDepB =10000 -200=9800
........
I need to get the values
AllDep. 10000 EUR
AllDep. - OnlyDepA=9900 EUR
AllDep. - OnlyDepB=9800 EUR
......
thanks
XavierSee if this is what you need:
SELECT S1.dep, S1.amt, S2.amt - S1.amt
FROM sales AS S1, sales AS S2
WHERE S2.dep = 'AllDep' ;
I'm assuming that DEP is unique. If it isn't then please post some
accurate DDL so that we don't have to guess what the keys and
constraints are.
David Portas
SQL Server MVP
--|||hello David,
great, your example works perfect, if the value DEP is unique.
In my case i have also a field WNr.
For a W the values are unique, also the value (Dep + WNr) are unique
for all records in the table. How must i modify the statement in this case.
w
39 All 1000
39 DepA 100
39 DepB 200
...
40 All 3000
40 DepA 400
40 DepB 500
...
41 All 2000
41 DepA 300
41 DepB 200
..
I also have to calculte somthing like
AllDep. -(OnlyDepA + OnlyDepA)=1000-(100+200)=700 for each w
thanks
Xavier|||Here's a slightly different approach
SELECT wnr, dep_a, dep_b, dep_all,
(dep_all - dep_a) AS expr1,
(dep_all - dep_a -dep_b) AS expr2
FROM
(SELECT wnr,
SUM(CASE WHEN dep = 'DepA' THEN amt END) AS dep_a,
SUM(CASE WHEN dep = 'DepB' THEN amt END) AS dep_b,
SUM(CASE WHEN dep = 'AllDep' THEN amt END) AS dep_all
FROM sales
GROUP BY wnr) AS T ;
David Portas
SQL Server MVP
--|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.
I hope that you know that a table cannot include a grand total, but
then you did not know that rows are not records; fields are not
columns; and tables are not files.
SELECT SUM(CASE WHEN dept_nbr = 'dept_1' THEN 0.00 ELSE foobar_amt END)
AS not_dept_1,
SUM(CASE WHEN dept_nbr = 'dept_2' THEN 0.00 ELSE foobar_amt END) AS
not_dept_2,
etc.
FROM Sales AS S1;|||David, thanks for your example, this is exactly for what i looked.
best regard,
Xavier
"David Portas" wrote:

> Here's a slightly different approach
> SELECT wnr, dep_a, dep_b, dep_all,
> (dep_all - dep_a) AS expr1,
> (dep_all - dep_a -dep_b) AS expr2
> FROM
> (SELECT wnr,
> SUM(CASE WHEN dep = 'DepA' THEN amt END) AS dep_a,
> SUM(CASE WHEN dep = 'DepB' THEN amt END) AS dep_b,
> SUM(CASE WHEN dep = 'AllDep' THEN amt END) AS dep_all
> FROM sales
> GROUP BY wnr) AS T ;
> --
> David Portas
> SQL Server MVP
> --
>

calculated sum

I have a dataset that returns a measure and a bunch of dimensions. What I need to be able to do is calculate a sum of this measure based on one dimension. ie..
Sum(measure) where dimension = "Top". Any ideas on how to accomplish this.No ideas? Seems to be a pretty basic function.|||Do you want the report user to interactively select a dimension value, and have the sum adjusted accordingly? In that case, you could set up a filter on the dataset, where the expression is the dimension column value, the operator is "=" and the value to compare against is the input parameter value.|||Nope. I just want to do a sum based on a dimension. Something like this.

Dataset1

Country Quantity
USA 1
USA 3
CANADA 1
MEXICO 3
CANADA 2

The sysntax I would use in Business Objects would be:

SUM(QUANTITY) WHERE(COUNTRY = "USA")

this expression would return 4.|||

Not sure if this solution will work for you, but you can add a Calculated Field to the Data Set, say: "FilteredQty", defined as (assuming Quantity is an integer):

CInt(iif(Fields!Country.Value = "USA", Fields!Quantity.Value, 0))

Then in your report you can use this expression:

Sum(Fields!FilteredQty.Value), wich should return 4 rather than 10

To make it dynamic, "USA" can be replaced by a report parameter.

|||Beautiful!! Works great. Thank you for your help.

calculated rows?

I've been waiting for this for a while. I'd like to be able to define a
table by specifying a set of numbers with the option of giving or not giving
bounds. Like, "all the integers between 200 and 500", or "all integers
greater than 2". Or, "all the Sundays between now and next year". There are
ways to do this already, but none of them are particularly elegant or can
flexibly represent unbounded sets. Is there any talk of adding a "calculated
rows" feature to SQL?
Hmmm. Just had an interesting thought- mix MatLab with SQL...
PaulPJ6 wrote:
> I've been waiting for this for a while. I'd like to be able to define a
> table by specifying a set of numbers with the option of giving or not givi
ng
> bounds. Like, "all the integers between 200 and 500", or "all integers
> greater than 2".
Huh? Where do you store an infinity of numbers? Presumably you just
mean a virtual table. In that case surely you would have to disallow
queries like the one you specified, since they will never return a
result:
SELECT * FROM numbers WHERE num >2 ;
-- how many rows does this return? !!!
Which queries are permitted against such tables and which ones aren't?
Given the potentially insoluble complexity of answering that question,
what is the advantage of "unbounded sets" over finite ones? These
requirements are commonly solved using auxiliary tables:
SELECT * FROM numbers
WHERE num >2
AND num <= 1000000 ;
SELECT dt
FROM Calendar
WHERE day_of_w = 'Sunday'
AND dt >= CURRENT_TIMESTAMP
AND dt < '20070101' ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||what do you mean by calculated rows?|||> I've been waiting for this for a while. I'd like to be able to define a
> table by specifying a set of numbers with the option of giving or not
> giving bounds. Like, "all the integers between 200 and 500", or "all
> integers greater than 2". Or, "all the Sundays between now and next year".
> There are ways to do this already, but none of them are particularly
> elegant or can flexibly represent unbounded sets. Is there any talk of
> adding a "calculated rows" feature to SQL?
Steve Kass has posted a UDF that will generate a table of sequential
numbers - obviously a finite set. I've found it to be very useful. Search
this NG if you want it.|||"PJ6" <nobody@.nowhere.net> wrote in message
news:%23n5v%23UwXGHA.1348@.TK2MSFTNGP05.phx.gbl...
> I've been waiting for this for a while. I'd like to be able to define a
> table by specifying a set of numbers with the option of giving or not
> giving bounds. Like, "all the integers between 200 and 500", or "all
> integers greater than 2". Or, "all the Sundays between now and next year".
> There are ways to do this already, but none of them are particularly
> elegant or can flexibly represent unbounded sets. Is there any talk of
> adding a "calculated rows" feature to SQL?
> Hmmm. Just had an interesting thought- mix MatLab with SQL...
>
With table valued user-defined functions you could always do this. But only
with the CLR integration does this get interesting.
Here's a TSQL function that enumerates an integer range. You could do
similar things for other types, or just wrap this function and do
conversions.
create function IntegerRange(@.start int, @.end int)
returns @.range table(i int primary key)
as
begin
declare @.i int
set @.i = @.start
while @.i <= @.end
begin
insert @.range(i) values (@.i)
set @.i = @.i + 1
end
return
end
This is OK for small ranges, but is quite expensive for larger ones.
Here's a CLR version that's vastly more efficient.
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None,
FillRowMethodName =
"IntegerRangeCLR_FillRow",
IsPrecise = true,
IsDeterministic = true,
TableDefinition = "i int",
Name = "IntegerRangeCLR")]
public static IEnumerable IntegerRangeCLR_Init(int begin, int end)
{
for (int i = begin; i <= end; i+=1)
{
yield return i;
}
}
public static void IntegerRangeCLR_FillRow(Object obj, out int i)
{
i = (int)obj;
}
};
Although these functions have the divantage that SQL can't gathere
statistics on them, and so a physical table with the enumarated range might
give you better overall query performance.
David|||"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1144939158.812211.120070@.z34g2000cwc.googlegroups.com...

> Which queries are permitted against such tables and which ones aren't?
A trivial difficulty since SQL is already a set-based language; only a few
new error conditions need to be detected so if the user really does SELECT *
from an infinite set, SQL could simply detect the problem up front and throw
an error such as:
Server: Msg 4208, Level 16, State 1, Line 1
Cannot query virtual tables representing unbounded sets without a completely
bounding WHERE clause.
Certainly there will still be cases where a user can make a rediculous yet
legal query from a virtual table, but that really adds no new danger as
problems like these are already possible, i.e. accidentally generating a
cartesian product in your result set.

> Given the potentially insoluble complexity of answering that question,
> what is the advantage of "unbounded sets" over finite ones?
Unbounded sets are better because the definition of the set is all that's
required - why waste space with real rows? I bet with a little tweaking the
query optimizer could take this new kind of table into account without any
problem, possibly even increasing performance over similar queries that use
traditional tables.
I see from another post that this becomes a little more practical to try
this using the CLR integration in SS2K5. That will be useful... but I would
argue that this should really be something built right into the database
engine; working with vitual sets (which currently must first be
materialized) is a design pattern that sees enough common usage that it's
perfectly reasonable to expect a deidcated feature with optimizations.
Paul
P.S. I know about "sqlwish", just posting to discuss. :)|||PJ6 wrote:
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:1144939158.812211.120070@.z34g2000cwc.googlegroups.com...
>
> A trivial difficulty since SQL is already a set-based language; only a few
> new error conditions need to be detected so if the user really does SELECT
*
> from an infinite set, SQL could simply detect the problem up front and thr
ow
> an error such as:
> Server: Msg 4208, Level 16, State 1, Line 1
> Cannot query virtual tables representing unbounded sets without a complete
ly
> bounding WHERE clause.
Is this really a trivial difficulty? When is an inner join against an
infinite set completely bounded? What about outer joins? What about a
WHERE clause based on a correlated subquery? I doubt it will be
feasible to detect any but the simplest queries that don't logically
terminate. It is certainly impossible to detect all recursive queries
that won't logically terminate (= the Halting Problem). Those queries
must fail at runtime due to stack and memory constraints.
A cartesian product against finite tables doesn't suffer quite the same
issue. The result is always finite and so the query will always
complete, given sufficient time and resources.
Recursive queries do have some of the qualities you are looking for. In
SQL Server 2005, create a view like this:
CREATE VIEW numbers AS
WITH n
AS (
SELECT CAST(0 AS INT) AS num
UNION ALL
SELECT n.num + 1
FROM n
WHERE num < 32767
)
SELECT num
FROM n;
GO
Now you can query it as follows:
SELECT num
FROM numbers
WHERE num<10 OPTION (MAXRECURSION 32767);
You still need the upper bound in the view though because SQL Server
won't rewrite the CTE query to include the num<10 condition. If the
optimiser was smart enough to push the WHERE clause down into the view
then an unbounded view might be a real possibility.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||What would a real world example be of where this would be useful?
I know a numbers table or a calendar table are often used for purposes like
this, and from what I have seen they work quite well. In the case of
calendar tables, they are often used because there is some business logic
attached to different dates, days of the w, etc.
I suppose you could use a complex query attached to a virtual numbers table
and then join to the results, which would do what you are proposing.
However, this will be time consuming and resource intensive (due to the
added logic in creating the result set) and would defeat the purpose for
using a calendar table to begin with.
I can see some use for a virtual numbers table, perhaps with a requirement
that it be bounded on both sides to prevent infinite queries, but when
creating one is so simple and requires so little resources, why worry about
a virtual one? It would certainly be nice to have, I'm just not certain
that it is at all necessary.
"PJ6" <nobody@.nowhere.net> wrote in message
news:%23n5v%23UwXGHA.1348@.TK2MSFTNGP05.phx.gbl...
> I've been waiting for this for a while. I'd like to be able to define a
> table by specifying a set of numbers with the option of giving or not
giving
> bounds. Like, "all the integers between 200 and 500", or "all integers
> greater than 2". Or, "all the Sundays between now and next year". There
are
> ways to do this already, but none of them are particularly elegant or can
> flexibly represent unbounded sets. Is there any talk of adding a
"calculated
> rows" feature to SQL?
> Hmmm. Just had an interesting thought- mix MatLab with SQL...
> Paul
>|||Here's a recursive sequence-generating function that's
very efficient and will generate as many integers as you'll
ever need (up to 2^64 of them). I got the idea from Itzik
Ben-Gan. On my 3 GHz desktop, it generates about
250,000 rows a second (from Query Analyzer with
the "Discard Results" option).
CREATE FUNCTION Sequence(
@.from BIGINT,
@.to BIGINT
) RETURNS TABLE AS RETURN
WITH L0(c) AS (
SELECT 1 UNION ALL SELECT 1
), L1(c) AS (
SELECT 1 FROM L0 AS A, L0 AS B
), L2(c) AS(
SELECT 1 FROM L1 AS A, L1 AS B
), L3(c) AS(
SELECT 1 FROM L2 AS A, L2 AS B
), L4(c) AS(
SELECT 1 FROM L3 AS A, L3 AS B
), L5(c) AS(
SELECT 1 FROM L4 AS A, L4 AS B
), L6(c) AS(
SELECT 1 FROM L5 AS A, L5 AS B
), Nums AS (
SELECT
ROW_NUMBER() OVER (ORDER BY c) AS n
FROM L5
)
SELECT n+@.from-1 AS Nbr
FROM Nums
WHERE n <= @.to-@.from+1
GO
-- Steve Kass
-- Drew University
PJ6 wrote:

>I've been waiting for this for a while. I'd like to be able to define a
>table by specifying a set of numbers with the option of giving or not givin
g
>bounds. Like, "all the integers between 200 and 500", or "all integers
>greater than 2". Or, "all the Sundays between now and next year". There are
>ways to do this already, but none of them are particularly elegant or can
>flexibly represent unbounded sets. Is there any talk of adding a "calculate
d
>rows" feature to SQL?
>Hmmm. Just had an interesting thought- mix MatLab with SQL...
>Paul
>
>|||"Steve Kass" <skass@.drew.edu> wrote in message
news:eB80wf2XGHA.3604@.TK2MSFTNGP02.phx.gbl...
> Here's a recursive sequence-generating function that's
> very efficient and will generate as many integers as you'll
> ever need (up to 2^64 of them). I got the idea from Itzik
> Ben-Gan. On my 3 GHz desktop, it generates about
> 250,000 rows a second (from Query Analyzer with
> the "Discard Results" option).
> CREATE FUNCTION Sequence(
> @.from BIGINT,
> @.to BIGINT
> ) RETURNS TABLE AS RETURN
> WITH L0(c) AS (
> SELECT 1 UNION ALL SELECT 1
> ), L1(c) AS (
> SELECT 1 FROM L0 AS A, L0 AS B
> ), L2(c) AS(
> SELECT 1 FROM L1 AS A, L1 AS B
> ), L3(c) AS(
> SELECT 1 FROM L2 AS A, L2 AS B
> ), L4(c) AS(
> SELECT 1 FROM L3 AS A, L3 AS B
> ), L5(c) AS(
> SELECT 1 FROM L4 AS A, L4 AS B
> ), L6(c) AS(
> SELECT 1 FROM L5 AS A, L5 AS B
> ), Nums AS (
> SELECT
> ROW_NUMBER() OVER (ORDER BY c) AS n
> FROM L5
> )
> SELECT n+@.from-1 AS Nbr
> FROM Nums
> WHERE n <= @.to-@.from+1
> GO
>
Well, I'm not often surprised by SQL. But wow. That's super-.
David

calculated members WHERE statement?

i am trying to figure out how to use MDX and a WHERE statement in the calculated member expression textbox. Every time i try i get a syntax error, and can't seem to find an example anywhere. Is it even possible?

I am trying to make a calculated member (measure) but I need to filter on only a few values of a DIM. I have seen how to write an MDX query and do this, but I need a permenant calculated measure.

Any insights? Thanks

Please keep in mind the difference between an MDX expression (used in defining a calculated member) and an MDX query (which can include a WHERE clause). You can try using Filter() in your MDX expression instead.|||i could never get that to work, i went down the road of making a named calculation and using that in my calculated measure

Calculated Members when generating a report model

I created and deployed calculated member as measures in my cube but when I generate a model in Reporting services the calculated members do not appear? Should they? or did I miss something? Anyone else experience this?

Thank you!

In get calculated members (calculated meaures) to surface in a report model, they have to be associated with a measure group. On the calculations tab in BIDS, click on the Calculation Properties button on the menu bar and then associate each calculated measure with a measure group. Recreate your report model and they should appear along with the measures that belong to that measure group.

HTH,

Dave Fackler

|||

Thank you, that was it! They are there now when I re-generate the model.

Janet

Calculated Members slow to display in Excel PivotTable

Hi,

I have created an Analysis Services 2005 cube, and am viewing it using an Excel PivotTable. When using Excel 2003, normal members display instantly, but when I place a calculated member in the PivotTable's data area it sits for several minutes before displaying. The calculated member (Gross Margin Percentage) was created with the expression:

[Measures].[Gross Margin]/[Measures].[Net Sale]

Net Sale is a data field from the Data Source View, while Gross Margin is a named calculation in the Data Source View (with the expression NetSale - Cost). When I use Excel 2000 the calculated member processes quickly. I cannot see any other option to give a percentage measure in the PivotTable, as I'm assuming that if I specify Gross Margin Percentage in the Data Source View it will not be aggregated correctly. Does anyone have any idea why Excel 2003 would give the slow performance, and whether there is any alternative way around it?

Thanks, Matt

Actually I prefer calculating the fields in a query and creating the cube using that query. Still slow? Create an index for that query Still slow? create a table. :) Hope it is MOLAP.|||

Hi, thanks for your response. The cube is fairly standard, being based on a few tables in my data warehouse. It is MOLAP. The reason I don't wish to calculate the Percentage field in a query is that the percentages will be aggregated incorrectly. For example if I had two records in the query as below:

Sales Margin MarginPercentage

10 5 0.5

20 5 0.25

Total 30 10 0.75

So as you can see the total margin percentage will give 0.75 when it should give 0.33. This is why I am using a calculated member in the cube rather than calculating the percentage within a query. I am wanting to know why this calculated member processes the same as all other members in Excel 2000, but is slow in Excel 2003. And also if there is anything I can do to get around the problem?

Thanks in advance, Matt

|||Nothing I can say. Ask the developpers of Excel 2003. :)|||

Did anyone tried with Excel 2007 ?

Philippe

|||

Could you please use Profiler to trace the MDX queries executed by Excel 2000, respectively Excel 2003, to understand the different between the queries?

Thank you

|||

A couple of thoughts:

i. Have you configured Non Empty Behaviour for the measure?

ii. I've had some problems with Excel 2003 hanging waiting for a query off a pivot table to execute. If I run the profiler and capture the MDX it still runs in a few seconds from BIDS. I'm guessing this particular issue is in the data transport layer because I get the same issue with ProClarity.

NWC

Calculated Members Problem

1. I got the price and the qty in the data source. when I create the
calculated member Amount = Qty * price, I found out the total is equal to the
total qty * total price.
How can I define the calculated member Amount = summation of (qty *
price).
2. secondly, I would like to count how many order line. How can I do it in
the calculated members?
"Kam" <Kam@.discussions.microsoft.com> wrote in message
news:55973F33-03AE-481D-91BF-18C5C3FEB85F@.microsoft.com...
> 1. I got the price and the qty in the data source. when I create the
> calculated member Amount = Qty * price, I found out the total is equal to
the
> total qty * total price.
> How can I define the calculated member Amount = summation of (qty *
> price).
>
Define a measure with source column = Qty * price

> 2. secondly, I would like to count how many order line. How can I do it in
> the calculated members?
>
Try defining a mesaure on OrderID_OrderLineID with aggregate function
"Count". But it depends on the structure of the fact table
Francesco Anti
|||I defined Qty * price.
but my problem is the total sales = total qty * total price. It is wrong.
How can I define the total sales = total (qty * price)?
"Francesco Anti" wrote:

> "Kam" <Kam@.discussions.microsoft.com> wrote in message
> news:55973F33-03AE-481D-91BF-18C5C3FEB85F@.microsoft.com...
> the
> Define a measure with source column = Qty * price
> Try defining a mesaure on OrderID_OrderLineID with aggregate function
> "Count". But it depends on the structure of the fact table
> Francesco Anti
>
>

Calculated Members Problem

1. I got the price and the qty in the data source. when I create the
calculated member Amount = Qty * price, I found out the total is equal to th
e
total qty * total price.
How can I define the calculated member Amount = summation of (qty *
price).
2. secondly, I would like to count how many order line. How can I do it in
the calculated members?"Kam" <Kam@.discussions.microsoft.com> wrote in message
news:55973F33-03AE-481D-91BF-18C5C3FEB85F@.microsoft.com...
> 1. I got the price and the qty in the data source. when I create the
> calculated member Amount = Qty * price, I found out the total is equal to
the
> total qty * total price.
> How can I define the calculated member Amount = summation of (qty *
> price).
>
Define a measure with source column = Qty * price

> 2. secondly, I would like to count how many order line. How can I do it in
> the calculated members?
>
Try defining a mesaure on OrderID_OrderLineID with aggregate function
"Count". But it depends on the structure of the fact table
Francesco Anti|||I defined Qty * price.
but my problem is the total sales = total qty * total price. It is wrong.
How can I define the total sales = total (qty * price)?
"Francesco Anti" wrote:

> "Kam" <Kam@.discussions.microsoft.com> wrote in message
> news:55973F33-03AE-481D-91BF-18C5C3FEB85F@.microsoft.com...
> the
> Define a measure with source column = Qty * price
>
> Try defining a mesaure on OrderID_OrderLineID with aggregate function
> "Count". But it depends on the structure of the fact table
> Francesco Anti
>
>