Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Tuesday, March 27, 2012

Calculated member - please help (SQL Server 2000)

hi,

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

Sunday, March 25, 2012

Calculated measure based on field in fact table that is not a measure in cube.

I have several fields in the fact table that are not measures in a cube. In this case I have a OrderEntryDateId, WantDateId, and InvoicedDateId. If the order has not invoiced the InvoiceDateId is 0 (zero).

My cube joins the fact table to the time dimension table on the wantDateId. The cube has measures for feet, dollars, pounds, material cost...

I want to create a calculated measure called "Invoiced Dollars" that is based on iff(invoiceDateId>0;TotalDollars,0) however invoiceDateId is not a measure nor is it linked to time in this cube.

Any ideas?

Hi. You could make the InvoiceDateID a member property of time dimension at the leaf level. You can then check the member property value in your calulated member. It might look something like this:

IIF(CINT(Time.Time.CurrentMember.Properties("InvoiceDateID")) > 0, TotalDollars, 0)

Drawbacks to this solution: (1) it only works at the leaf level of the time dimension, (2) Probably slow because of the conversion of the member property value.

Hope this helps - Paul Goldy

|||

I already played with this a bit this afternoon and it is not what I need.

I guess the best way to do this is to add a column to the fact table so it can work at all levels and be pre-aggregated.

Thanks!

Calculated fields on olap pivottable in excel 2007

Is there a way to add calculated fields in excel 2007 to a pivot table, connected to a SSAS cube?

Meaning that is calculated on the fly automatically while drilling up/down...

I do not think so. The formulas button is disabled. Formulas have to be server side MDX calculated members. Same in Excel 2003

You will also note some other diffences like Grouping may require security access to cube metadata in order to work.

Philippe

|||This is quite a disadvantage! Hopefully the kpi wizard and the set selector of ProClarity will be integrated into excel!

Calculated fields in Matrix

Hi!

I have a calculated field in a dataset, Productivity, defined by this expression:

Fields!BCM.Value/Fields!MINUTES.Value

When I use it on a table, everything works fine. But when I try to use it on a matrix, I get an error
(#ERROR) on the field.
Why does it happen? Can't I use calculated fields on matrix?

Thank you!

Dear,

Sure , u will get the error beause u are using the field in matrix but when u define the function u are not passing the matrix refrence.

eg:

=iif(inscope(Sum(Fields!OrderQty.Value, "MatrixSource")),sum(Fields!OrderQty.Value),sum(Fields!OrderQty.Value)/Sum(Fields!OrderQty.Value, "MatrixSource"))

HTH

from

sufian

Calculated Fields

I have two questions regarding calculated fields.
I have a report with two datasets.
Issue 1:
Dataset 1 queries a table that contains configuration information. This
table has one row.
I would like to create a calculated field that divides the value of a
column in this one row but another value in the one row. The problem
appears to be that SRS is expecting the query to return 1 or more rows,
and thus only likes to let me do aggregations on the output from the
dataset. Is there a way to either tell it that there will only be one
row, or a different way to extract the config info from the database
that makes more sense?
Issue 2:
I would then like to use the output of the calculated field from issue
one as part of a calculated field in the second dataset. This seems to
be a problem, as SRS complains with the following statement:
=Sum(Fields!INVOICEAMOUNT.Value, "DailySalesDS") /
Fields!DailyInvoiceProRateMultiplier.Value, "InputDataDS"
Will not compile. I get errors regarding aggregates in report
parameters and about using something from another dataset.
My guess is that I am going about this the wrong way. Any help is
appreciated.In case you missed it, I have answered your questions already in the
"Computed Fields/Multiple Datasources" thread yesterday.
--
This posting is provided "AS IS" with no warranties, and confers no rights.
"Hunter Hillegas" <hunter.hillegas@.gmail.com> wrote in message
news:chtc25$sd9@.odbk17.prod.google.com...
> I have two questions regarding calculated fields.
> I have a report with two datasets.
> Issue 1:
> Dataset 1 queries a table that contains configuration information. This
> table has one row.
> I would like to create a calculated field that divides the value of a
> column in this one row but another value in the one row. The problem
> appears to be that SRS is expecting the query to return 1 or more rows,
> and thus only likes to let me do aggregations on the output from the
> dataset. Is there a way to either tell it that there will only be one
> row, or a different way to extract the config info from the database
> that makes more sense?
> Issue 2:
> I would then like to use the output of the calculated field from issue
> one as part of a calculated field in the second dataset. This seems to
> be a problem, as SRS complains with the following statement:
> =Sum(Fields!INVOICEAMOUNT.Value, "DailySalesDS") /
> Fields!DailyInvoiceProRateMultiplier.Value, "InputDataDS"
> Will not compile. I get errors regarding aggregates in report
> parameters and about using something from another dataset.
> My guess is that I am going about this the wrong way. Any help is
> appreciated.
>sql

Calculated field values?

Dear All,

I have a table called CustomerWorkPlan and some of the fields are
1. PlannedID - Primary Key
2. Planned_Start_Date -Datetime field
3. Actual_Start_Date -Datetime field

I wanted to write a query in the from of StoreProcedures which will select some of the

fields and a given field name "Start Date" with the values coming from

Actual_Start_Date if not null else from Planned_Start_Date.

How can I achieve this query? Need help.

create table #tt (plannedid int ,Planned_Start_Date datetime,Actual_Start_Date datetime)
insert into #tt select 1,null,getdate()
insert into #tt select 1,getdate()-1,null

select *,isnull(Actual_Start_Date,Planned_Start_Date)as startdate
from #tt

check this

Madhu

|||

Hi,

is this answer, dear?

Code Snippet

Select PlannedId,

case

when Actual_Start_Date is null then Planned_Start_Date

else Planned_Start_Date

end

from

your table name

|||

masum,

Your suggestion will only provide the Planned_Start_Date -it will never provide the Actual_Start_Date.

Can you see why it is not a correct answer to the question?

Thursday, March 22, 2012

Calculated field is calculated wrong

Hi there,
(SQL Server 2000, running on Windows 2000 server, all service packs
installed)
I have a table with columns A, B and C, all three are tinyint. I added a
fourth column D, that has this formula:
(A * 3) + (B * 2) + C
This doesn't get calculated well, for example:
A = 8, B = 10, C = 10 -> D = 57
I worked around it by changing the formula into A + A + A + B + B + C which
works correctly, still I don't understand what is wrong with the first
formula... or is it a bug?
Any ideas are appreciated.
RayI could not reproduce this:
USE tempdb
CREATE TABLE t(A tinyint, B tinyint, C tinyint, D AS (A * 3) + (B * 2) + C)
INSERT INTO t (A, B, C) values(8, 10, 10)
SELECT * FROM t
A B C D
-- -- -- --
8 10 10 54
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"R. van Laake" <nospam_r.vanlaake@.dfk.nl> wrote in message
news:41f4c08d$0$14112$d456229f@.news.routit.net...
> Hi there,
> (SQL Server 2000, running on Windows 2000 server, all service packs
> installed)
> I have a table with columns A, B and C, all three are tinyint. I added a
> fourth column D, that has this formula:
> (A * 3) + (B * 2) + C
> This doesn't get calculated well, for example:
> A = 8, B = 10, C = 10 -> D = 57
> I worked around it by changing the formula into A + A + A + B + B + C whi
ch
> works correctly, still I don't understand what is wrong with the first
> formula... or is it a bug?
> Any ideas are appreciated.
> Ray
>
>|||Hmmm... still I get it.
I entered the formula using Enterprise Manager. When I enter:
(A * 3) + (B * 2) + C
EM changes it into:
([A]*3 + [B]*2 + [C])
which should be correct of course... but it does get calculated wrong
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:uPiS6jfAFHA.4008@.TK2MSFTNGP09.phx.gbl...
> I could not reproduce this:
> USE tempdb
> CREATE TABLE t(A tinyint, B tinyint, C tinyint, D AS (A * 3) + (B * 2) +
C)
> INSERT INTO t (A, B, C) values(8, 10, 10)
> SELECT * FROM t
> A B C D
> -- -- -- --
> 8 10 10 54
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> http://www.sqlug.se/
>
> "R. van Laake" <nospam_r.vanlaake@.dfk.nl> wrote in message
> news:41f4c08d$0$14112$d456229f@.news.routit.net...
which
>|||Did you run the code that Tibor posted? What result did you get? If in
doubt avoid Enterprise Manager for data and schema changes - TSQL code
gives you more control. However, I couldn't reproduce the problem even
using EM - the result I get is 54.
If you still think there's a problem after trying Tibor's code then
post a complete, tested set of steps to reproduce the problem: CREATE
TABLE, INSERT followed by the exact steps you performed in EM. Also
tell us your product edition, version and service pack.
--
David Portas
SQL Server MVP
--|||Tibor's code runs just fine. I just changed my workaround formula
(A+A+A+B+B+C) back to (A*3)+(B*2)+C and now it does seem to work
correctly... I really don't understand. I am 100% sure there was no typing
error, and that the calculation was wrong. I even changed some values in the
A, B and C columns and saw a wrong calculation over and over again.
I will keep the (A*3)+(B*2)+C formula and if I see that it goes wrong
again, post here again.
Thanks for all your help,
Ray
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1106563785.886482.117750@.c13g2000cwb.googlegroups.com...
> Did you run the code that Tibor posted? What result did you get? If in
> doubt avoid Enterprise Manager for data and schema changes - TSQL code
> gives you more control. However, I couldn't reproduce the problem even
> using EM - the result I get is 54.
> If you still think there's a problem after trying Tibor's code then
> post a complete, tested set of steps to reproduce the problem: CREATE
> TABLE, INSERT followed by the exact steps you performed in EM. Also
> tell us your product edition, version and service pack.
> --
> David Portas
> SQL Server MVP
> --
>

Calculated Field (GPA)

I have a table and I need to have a calculated field which calculates GPA based on the letter grade they have, and only those grades that have subject as CHEM or BIO.

here is a sample table:

Term

ID

LastName

FirstName

CRN

Subject

LetterGrade

Calc GPA

20072

1

Doe

John

1234

CHEM

B

20072

1

Doe

John

3214

BIO

A

20072

1

Doe

John

4321

LAW

B

20072

2

Bauer

Jack

1234

CHEM

A

20072

2

Bauer

Jack

3214

BIO

C

20072

2

Bauer

Jack

5467

FIN

B

A = 4.0

B = 3.0

C = 2.0

D = 1.0

Here ya go:

Code Snippet

declare @.t table (Term char(5), ID int, LastName varchar(50), FirstName varchar(50),

CRN int, Subject varchar(20), LetterGrade char(1))

insert into @.t

select '20072', 1, 'Doe', 'John', 1234, 'CHEM', 'B'

union all select '20072', 1, 'Doe', 'John', 3214, 'BIO', 'A'

union all select '20072', 1, 'Doe', 'John', 4321, 'LAW', 'B'

union all select '20072', 2, 'Bauer', 'Jack', 1234, 'CHEM', 'A'

union all select '20072', 2, 'Bauer', 'Jack', 3214, 'BIO', 'C'

union all select '20072', 2, 'Bauer', 'Jack', 5467, 'FIN', 'B'

declare @.GradeEquiv table (LetterGrade char(1), NumericGrade numeric(2, 1))

insert into @.GradeEquiv

select 'A', 4.0

union all select 'B', 3.0

union all select 'C', 2.0

union all select 'D', 1.0

select t.Term, t.ID, t.LastName, t.FirstName, avg(ge.NumericGrade) as GPA

from @.t t

inner join @.GradeEquiv ge

on t.LetterGrade = ge.LetterGrade

where Subject in ('CHEM', 'BIO')

group by t.Term, t.ID, t.LastName, t.FirstName

|||

Try:

;with Grade

as

(

select '20072' as Term, 1 as ID, 'Doe' as LastName, 'John' as FirstName, 1234 CRN, 'CHEM' as [Subject], 'B' as LetterGrade

union all select '20072', 1, 'Doe', 'John', 3214, 'BIO', 'A'

union all select '20072', 1, 'Doe', 'John', 4321, 'LAW', 'B'

union all select '20072', 2, 'Bauer', 'Jack', 1234, 'CHEM', 'A'

union all select '20072', 2, 'Bauer', 'Jack', 3214, 'BIO', 'C'

union all select '20072', 2, 'Bauer', 'Jack', 5467, 'FIN', 'B'

)

select

Term,

ID,

LastName,

FirstName,

CRN,

[Subject],

LetterGrade,

AVG(

case LetterGrade

when 'A' then 4.0

when 'B' then 3.0

when 'C' then 2.0

when 'D' then 1.0

end

) OVER(partition by Term, ID) as GPA

from

Grade

where

[Subject] in ('CHEM', 'BIO');

AMB

|||

Thanks guys, I'll try those out now.

|||

Is there a way to still show the other classes, like LAW for instance, but to still have the GPA from the other calculated classes?

|||

Try:

;with Grade

as

(

select '20072' as Term, 1 as ID, 'Doe' as LastName, 'John' as FirstName, 1234 CRN, 'CHEM' as [Subject], 'B' as LetterGrade

union all select '20072', 1, 'Doe', 'John', 3214, 'BIO', 'A'

union all select '20072', 1, 'Doe', 'John', 4321, 'LAW', 'B'

union all select '20072', 2, 'Bauer', 'Jack', 1234, 'CHEM', 'A'

union all select '20072', 2, 'Bauer', 'Jack', 3214, 'BIO', 'C'

union all select '20072', 2, 'Bauer', 'Jack', 5467, 'FIN', 'B'

)

select

Term,

ID,

LastName,

FirstName,

CRN,

[Subject],

LetterGrade,

SUM(

case

when [Subject] in ('CHEM', 'BIO') and LetterGrade = 'A' then 4.0

when [Subject] in ('CHEM', 'BIO') and LetterGrade = 'B' then 3.0

when [Subject] in ('CHEM', 'BIO') and LetterGrade = 'C' then 2.0

when [Subject] in ('CHEM', 'BIO') and LetterGrade = 'D' then 1.0

end

) OVER(partition by Term, ID) /

nullif(

SUM(

case

when [Subject] in ('CHEM', 'BIO') then 1

else 0

end

) OVER(partition by Term, ID), 0) as GPA

from

Grade;

AMB

Calculated field

can I create a field whose values will be derived from
other fields in the table without writing a stored proc or
script? For example if I have a table called Salary with
three fields: hours, rate and GrossPay. I want the
grosspay field to be updated automatically if values have
been provided for the hours and rate fields. Is this
feasible?
Thanks for your help in advance.
This is called a computed column. The values are not stored but are
calculated when a result set is requested. The syntax is documented under
the the CREATE TABLE and ALTER TABLE commands in BOL (Books On-Line).
Geoff N. Hiten
Microsoft SQL Server MVP
Senior Database Administrator
Careerbuilder.com
I support the Professional Association for SQL Server
www.sqlpass.org
"lala" <anonymous@.discussions.microsoft.com> wrote in message
news:194b01c4aafa$39e6cef0$7d02280a@.phx.gbl...
> can I create a field whose values will be derived from
> other fields in the table without writing a stored proc or
> script? For example if I have a table called Salary with
> three fields: hours, rate and GrossPay. I want the
> grosspay field to be updated automatically if values have
> been provided for the hours and rate fields. Is this
> feasible?
> Thanks for your help in advance.
|||lala,
I believe you can use a trigger to accomplish what you are asking. in the
BOL navigate to 'create trigger', and you can look at some examples there.
essentially, every time someone updates those columns, the trigger should be
able to poulate the third column.
hth
"lala" wrote:

> can I create a field whose values will be derived from
> other fields in the table without writing a stored proc or
> script? For example if I have a table called Salary with
> three fields: hours, rate and GrossPay. I want the
> grosspay field to be updated automatically if values have
> been provided for the hours and rate fields. Is this
> feasible?
> Thanks for your help in advance.
>
|||In addition to the other posts: consider having a view where you define the calculated columns and
use that view. This way you don't have to "litter" your tables with calculated values.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"lala" <anonymous@.discussions.microsoft.com> wrote in message
news:194b01c4aafa$39e6cef0$7d02280a@.phx.gbl...
> can I create a field whose values will be derived from
> other fields in the table without writing a stored proc or
> script? For example if I have a table called Salary with
> three fields: hours, rate and GrossPay. I want the
> grosspay field to be updated automatically if values have
> been provided for the hours and rate fields. Is this
> feasible?
> Thanks for your help in advance.

Calculated field

can I create a field whose values will be derived from
other fields in the table without writing a stored proc or
script? For example if I have a table called Salary with
three fields: hours, rate and GrossPay. I want the
grosspay field to be updated automatically if values have
been provided for the hours and rate fields. Is this
feasible'
Thanks for your help in advance.This is called a computed column. The values are not stored but are
calculated when a result set is requested. The syntax is documented under
the the CREATE TABLE and ALTER TABLE commands in BOL (Books On-Line).
--
Geoff N. Hiten
Microsoft SQL Server MVP
Senior Database Administrator
Careerbuilder.com
I support the Professional Association for SQL Server
www.sqlpass.org
"lala" <anonymous@.discussions.microsoft.com> wrote in message
news:194b01c4aafa$39e6cef0$7d02280a@.phx.gbl...
> can I create a field whose values will be derived from
> other fields in the table without writing a stored proc or
> script? For example if I have a table called Salary with
> three fields: hours, rate and GrossPay. I want the
> grosspay field to be updated automatically if values have
> been provided for the hours and rate fields. Is this
> feasible'
> Thanks for your help in advance.|||lala,
I believe you can use a trigger to accomplish what you are asking. in the
BOL navigate to 'create trigger', and you can look at some examples there.
essentially, every time someone updates those columns, the trigger should be
able to poulate the third column.
hth
"lala" wrote:
> can I create a field whose values will be derived from
> other fields in the table without writing a stored proc or
> script? For example if I have a table called Salary with
> three fields: hours, rate and GrossPay. I want the
> grosspay field to be updated automatically if values have
> been provided for the hours and rate fields. Is this
> feasible'
> Thanks for your help in advance.
>|||In addition to the other posts: consider having a view where you define the calculated columns and
use that view. This way you don't have to "litter" your tables with calculated values.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"lala" <anonymous@.discussions.microsoft.com> wrote in message
news:194b01c4aafa$39e6cef0$7d02280a@.phx.gbl...
> can I create a field whose values will be derived from
> other fields in the table without writing a stored proc or
> script? For example if I have a table called Salary with
> three fields: hours, rate and GrossPay. I want the
> grosspay field to be updated automatically if values have
> been provided for the hours and rate fields. Is this
> feasible'
> Thanks for your help in advance.sql

Calculated columns...

Hello,
can anyone help me with this?
SELECT (A+B) AS X FROM TABLE WHERE X = 'sqdf'
The point here is, if I use the following query
SELECT (A+B) AS X FROM TABLE WHERE (A+B) = 'sqdf'
the thing works, but for programming-technical reasons a have to use X
SELECT (A+B) AS X FROM TABLE WHERE X = 'sqdf'
What's wrong here?
Regards,
Kurt RogiersWHERE is evaluated before the field list, meaning that when you run
this, there is no column named "X" when the WHERE clause is evaluated.
Something like this will achieve the desired effect:
SELECT X
FROM (SELECT (A+B) AS X FROM TABLE) AS calcX
WHERE X = 'sqdf'
Kurt Rogiers wrote:
> Hello,
> can anyone help me with this?
> SELECT (A+B) AS X FROM TABLE WHERE X = 'sqdf'
> The point here is, if I use the following query
> SELECT (A+B) AS X FROM TABLE WHERE (A+B) = 'sqdf'
> the thing works, but for programming-technical reasons a have to use X
> SELECT (A+B) AS X FROM TABLE WHERE X = 'sqdf'
> What's wrong here?
> Regards,
> Kurt Rogiers|||You cannot use column aliases like this. You can only reference a column
alias in an ORDER BY clause, or outside of an inline query.
You can change the way you are coding this, to eliminate the "
programming-technical reasons " that require you to use "X".
You can also try one of these approaches:
select X from
(
SELECT (A+B) AS X FROM TABLE
)
where X = 'sqdf'
Create view MyView as
SELECT (A+B) AS X FROM TABLE
select X from MyView where X='sqdf'
"Kurt Rogiers" <k.rogiers@.skynet.be> wrote in message
news:%23jLUu%23viGHA.4056@.TK2MSFTNGP02.phx.gbl...
> Hello,
> can anyone help me with this?
> SELECT (A+B) AS X FROM TABLE WHERE X = 'sqdf'
> The point here is, if I use the following query
> SELECT (A+B) AS X FROM TABLE WHERE (A+B) = 'sqdf'
> the thing works, but for programming-technical reasons a have to use X
> SELECT (A+B) AS X FROM TABLE WHERE X = 'sqdf'
> What's wrong here?
> Regards,
> Kurt Rogiers
>|||Hello,
life can be SOOO easy!!!
Thanks a lot, the solution works wonderful
Regard,
Kurt
"Jim Underwood" <james.underwoodATfallonclinic.com> schreef in bericht
news:O%23wf3IwiGHA.1936@.TK2MSFTNGP04.phx.gbl...
> You cannot use column aliases like this. You can only reference a column
> alias in an ORDER BY clause, or outside of an inline query.
> You can change the way you are coding this, to eliminate the "
> programming-technical reasons " that require you to use "X".
> You can also try one of these approaches:
> select X from
> (
> SELECT (A+B) AS X FROM TABLE
> )
> where X = 'sqdf'
>
> Create view MyView as
> SELECT (A+B) AS X FROM TABLE
> select X from MyView where X='sqdf'
>
> "Kurt Rogiers" <k.rogiers@.skynet.be> wrote in message
> news:%23jLUu%23viGHA.4056@.TK2MSFTNGP02.phx.gbl...
>sql

calculated columns in a table

Hi,
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

Calculated Columns

Hi,
In have a select query with one calculated column in the select column
collection. When I change the select FROM clause from table name to a table
defined with select statement, I get error. The query is:
DECLARE @.YearsSet TABLE (
[YEARCOLTIME] VARCHAR(8000))
INSERT @.YearsSet
SELECT [YEARCOLTIME]
FROM (SELECT *,
(CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
FROM [MY_TABLE]) AS [TIMELEVELTABLE]
WHERE [YEARCOLTIME] = N'2000'
OR [YEARCOLTIME] = N'2001'
GROUP BY [YEARCOLTIME]
DECLARE @.ProductsSet TABLE (
[PRODUCTS] VARCHAR(8000))
INSERT @.ProductsSet
SELECT [PRODUCTS]
FROM [MY_TABLE]
WHERE [PRODUCTS] = N'IES XXI JK'
OR [PRODUCTS] = N'Troy Sys 4'
OR [PRODUCTS] = N'Core Series 12'
GROUP BY [PRODUCTS]
SELECT [TIMELEVELTABLE].[DISTRIBUTION CENTER],
[@.YEARSSET].[YEARCOLTIME],
(SUM(CAST([TIMELEVELTABLE].[SALES AMT] AS FLOAT))) AS
[AGGREGATEDSALES AMT],
(SELECT AVG([SALES AMT])
FROM (SELECT (SUM(CAST([FORMULATIMELEVELTABLE].[SALES AMT] AS
FLOAT))) AS [SALES AMT]
FROM (SELECT *,
(CAST(YEAR([TIME]) AS VARCHAR)) AS
[YEARCOLTIME]
FROM [MY_TABLE]) AS [FORMULATIMELEVELTABLE]
INNER JOIN @.ProductsSet AS [@.PRODUCTSSET]
ON [@.PRODUCTSSET].[PRODUCTS] =
[FORMULATIMELEVELTABLE].[PRODUCTS]
WHERE [TIMELEVELTABLE].[DISTRIBUTION CENTER] =
[FORMULATIMELEVELTABLE].[DISTRIBUTION CENTER]
AND [@.YEARSSET].[YEARCOLTIME] =
[FORMULATIMELEVELTABLE].[YEARCOLTIME]
GROUP BY [@.PRODUCTSSET].[PRODUCTS]) AS [FUNCTIONTABLE]) AS
[AGGREGATEDFORMULA0]
FROM (SELECT *,
(CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
FROM [MY_TABLE]) AS [TIMELEVELTABLE]
INNER JOIN @.YearsSet AS [@.YEARSSET]
ON [@.YEARSSET].[YEARCOLTIME] = [TIMELEVELTABLE].[YEARCOLTIME]
GROUP BY [TIMELEVELTABLE].[DISTRIBUTION CENTER],
[@.YEARSSET].[YEARCOLTIME]
(Please copy paste the query somewhere else, it’s much easier to read and
understand the problem)
The error I get is:
Server: Msg 207, Level 16, State 3, Line 24
Invalid column name 'DISTRIBUTION CENTER'.Can you replace the * with the column names and then try executing it and
repaste the query if it doesn't work (with the error message).
Thanks
Omnibuzz|||Hi Omnibuzz, thanks for the quick response, but its not working. Here is the
query again:
DECLARE @.YearsSet TABLE (
[YEARCOLTIME] VARCHAR(8000))
INSERT @.YearsSet
SELECT [YEARCOLTIME]
FROM (SELECT *,
(CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
FROM [MY_TABLE]) AS [TIMELEVELTABLE]
WHERE [YEARCOLTIME] = N'2000'
OR [YEARCOLTIME] = N'2001'
GROUP BY [YEARCOLTIME]
DECLARE @.ProductsSet TABLE (
[PRODUCTS] VARCHAR(8000))
INSERT @.ProductsSet
SELECT [PRODUCTS]
FROM [MY_TABLE]
WHERE [PRODUCTS] = N'IES XXI JK'
OR [PRODUCTS] = N'Troy Sys 4'
OR [PRODUCTS] = N'Core Series 12'
GROUP BY [PRODUCTS]
SELECT [TIMELEVELTABLE].[DISTRIBUTION CENTER],
[@.YEARSSET].[YEARCOLTIME],
(SUM(CAST([TIMELEVELTABLE].[SALES AMT] AS FLOAT))) AS
[AGGREGATEDSALES AMT],
(SELECT AVG([SALES AMT])
FROM (SELECT (SUM(CAST([FORMULATIMELEVELTABLE].[SALES AMT] AS
FLOAT))) AS [SALES AMT]
FROM (SELECT [PRODUCTS],
[DISTRIBUTION CENTER],
[SALES AMT],
(CAST(YEAR([TIME]) AS VARCHAR)) AS
[YEARCOLTIME]
FROM [MY_TABLE]) AS [FORMULATIMELEVELTABLE]
INNER JOIN @.ProductsSet AS [@.PRODUCTSSET]
ON [@.PRODUCTSSET].[PRODUCTS] =
[FORMULATIMELEVELTABLE].[PRODUCTS]
WHERE [TIMELEVELTABLE].[DISTRIBUTION CENTER] =
[FORMULATIMELEVELTABLE].[DISTRIBUTION CENTER]
AND [@.YEARSSET].[YEARCOLTIME] =
[FORMULATIMELEVELTABLE].[YEARCOLTIME]
GROUP BY [@.PRODUCTSSET].[PRODUCTS]) AS [FUNCTIONTABLE]) AS
[AGGREGATEDFORMULA0]
FROM (SELECT [PRODUCTS],
[DISTRIBUTION CENTER],
[SALES AMT],
(CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
FROM [MY_TABLE]) AS [TIMELEVELTABLE]
INNER JOIN @.YearsSet AS [@.YEARSSET]
ON [@.YEARSSET].[YEARCOLTIME] = [TIMELEVELTABLE].[YEARCOLTIME]
GROUP BY [TIMELEVELTABLE].[DISTRIBUTION CENTER],
[@.YEARSSET].[YEARCOLTIME]
"Omnibuzz" wrote:

> Can you replace the * with the column names and then try executing it and
> repaste the query if it doesn't work (with the error message).
> Thanks
> Omnibuzz|||Sorry, this is the updated query:
DECLARE @.YearsSet TABLE (
[YEARCOLTIME] VARCHAR(8000))
INSERT @.YearsSet
SELECT [YEARCOLTIME]
FROM (SELECT [PRODUCTS],
[DISTRIBUTION CENTER],
[SALES AMT],
(CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
FROM [MY_TABLE]) AS [TIMELEVELTABLE]
WHERE [YEARCOLTIME] = N'2000'
OR [YEARCOLTIME] = N'2001'
GROUP BY [YEARCOLTIME]
DECLARE @.ProductsSet TABLE (
[PRODUCTS] VARCHAR(8000))
INSERT @.ProductsSet
SELECT [PRODUCTS]
FROM [MY_TABLE]
WHERE [PRODUCTS] = N'IES XXI JK'
OR [PRODUCTS] = N'Troy Sys 4'
OR [PRODUCTS] = N'Core Series 12'
GROUP BY [PRODUCTS]
SELECT [TIMELEVELTABLE].[DISTRIBUTION CENTER],
[@.YEARSSET].[YEARCOLTIME],
(SUM(CAST([TIMELEVELTABLE].[SALES AMT] AS FLOAT))) AS
[AGGREGATEDSALES AMT],
(SELECT AVG([SALES AMT])
FROM (SELECT (SUM(CAST([FORMULATIMELEVELTABLE].[SALES AMT] AS
FLOAT))) AS [SALES AMT]
FROM (SELECT [PRODUCTS],
[DISTRIBUTION CENTER],
[SALES AMT],
(CAST(YEAR([TIME]) AS VARCHAR)) AS
[YEARCOLTIME]
FROM [MY_TABLE]) AS [FORMULATIMELEVELTABLE]
INNER JOIN @.ProductsSet AS [@.PRODUCTSSET]
ON [@.PRODUCTSSET].[PRODUCTS] =
[FORMULATIMELEVELTABLE].[PRODUCTS]
WHERE [TIMELEVELTABLE].[DISTRIBUTION CENTER] =
[FORMULATIMELEVELTABLE].[DISTRIBUTION CENTER]
AND [@.YEARSSET].[YEARCOLTIME] =
[FORMULATIMELEVELTABLE].[YEARCOLTIME]
GROUP BY [@.PRODUCTSSET].[PRODUCTS]) AS [FUNCTIONTABLE]) AS
[AGGREGATEDFORMULA0]
FROM (SELECT [PRODUCTS],
[DISTRIBUTION CENTER],
[SALES AMT],
(CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
FROM [MY_TABLE]) AS [TIMELEVELTABLE]
INNER JOIN @.YearsSet AS [@.YEARSSET]
ON [@.YEARSSET].[YEARCOLTIME] = [TIMELEVELTABLE].[YEARCOLTIME]
GROUP BY [TIMELEVELTABLE].[DISTRIBUTION CENTER],
[@.YEARSSET].[YEARCOLTIME]
"Omnibuzz" wrote:

> Can you replace the * with the column names and then try executing it and
> repaste the query if it doesn't work (with the error message).
> Thanks
> Omnibuzz|||Can you post the create script for my_table.
"Aviad" wrote:
> Hi Omnibuzz, thanks for the quick response, but its not working. Here is t
he
> query again:
> DECLARE @.YearsSet TABLE (
> [YEARCOLTIME] VARCHAR(8000))
> INSERT @.YearsSet
> SELECT [YEARCOLTIME]
> FROM (SELECT *,
> (CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
> FROM [MY_TABLE]) AS [TIMELEVELTABLE]
> WHERE [YEARCOLTIME] = N'2000'
> OR [YEARCOLTIME] = N'2001'
> GROUP BY [YEARCOLTIME]
> DECLARE @.ProductsSet TABLE (
> [PRODUCTS] VARCHAR(8000))
> INSERT @.ProductsSet
> SELECT [PRODUCTS]
> FROM [MY_TABLE]
> WHERE [PRODUCTS] = N'IES XXI JK'
> OR [PRODUCTS] = N'Troy Sys 4'
> OR [PRODUCTS] = N'Core Series 12'
> GROUP BY [PRODUCTS]
> SELECT [TIMELEVELTABLE].[DISTRIBUTION CENTER],
> [@.YEARSSET].[YEARCOLTIME],
> (SUM(CAST([TIMELEVELTABLE].[SALES AMT] AS FLOAT))) AS
> [AGGREGATEDSALES AMT],
> (SELECT AVG([SALES AMT])
> FROM (SELECT (SUM(CAST([FORMULATIMELEVELTABLE].[SALES AMT] AS
> FLOAT))) AS [SALES AMT]
> FROM (SELECT [PRODUCTS],
> [DISTRIBUTION CENTER],
> [SALES AMT],
> (CAST(YEAR([TIME]) AS VARCHAR)) AS
> [YEARCOLTIME]
> FROM [MY_TABLE]) AS [FORMULATIMELEVELTABLE]
> INNER JOIN @.ProductsSet AS [@.PRODUCTSSET]
> ON [@.PRODUCTSSET].[PRODUCTS] =
> [FORMULATIMELEVELTABLE].[PRODUCTS]
> WHERE [TIMELEVELTABLE].[DISTRIBUTION CENTER] =
> [FORMULATIMELEVELTABLE].[DISTRIBUTION CENTER]
> AND [@.YEARSSET].[YEARCOLTIME] =
> [FORMULATIMELEVELTABLE].[YEARCOLTIME]
> GROUP BY [@.PRODUCTSSET].[PRODUCTS]) AS [FUNCTIONTABLE]) AS
> [AGGREGATEDFORMULA0]
> FROM (SELECT [PRODUCTS],
> [DISTRIBUTION CENTER],
> [SALES AMT],
> (CAST(YEAR([TIME]) AS VARCHAR)) AS [YEARCOLTIME]
> FROM [MY_TABLE]) AS [TIMELEVELTABLE]
> INNER JOIN @.YearsSet AS [@.YEARSSET]
> ON [@.YEARSSET].[YEARCOLTIME] = [TIMELEVELTABLE].[YEARCOLTIME]
> GROUP BY [TIMELEVELTABLE].[DISTRIBUTION CENTER],
> [@.YEARSSET].[YEARCOLTIME]
>
> "Omnibuzz" wrote:
>|||Here it is:
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[My_Table]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[My_Table]
GO
CREATE TABLE [dbo].[My_Table] (
[Products] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
[Distribution Center] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[Sales Amt] [float] NULL ,
[Time] [datetime] NULL ,
[Col100] [int] NOT NULL
) ON [PRIMARY]
GO
"Omnibuzz" wrote:
> Can you post the create script for my_table.
>
> "Aviad" wrote:
>|||Hi Aviad,
The create table script was having a syntax error. Fixed it.
But here it seems to work fine in my machine :)
try removing the distribution center column from the select and the group by
of the final query and try..|||Hi,
Its not working here, somehow it doesn’t "recognize" the column:
[TIMELEVELTABLE].[DISTRIBUTION CENTER] in the row:
WHERE [TIMELEVELTABLE].[DISTRIBUTION CENTER] =
[FORMULATIMELEVELTABLE].[DISTRIBUTION CENTER].
Which in the calculated column.
"Omnibuzz" wrote:

> Hi Aviad,
> The create table script was having a syntax error. Fixed it.
> But here it seems to work fine in my machine :)
> try removing the distribution center column from the select and the group
by
> of the final query and try..
>|||and the fixed script:
if exists (select * from dbo.sysobjects where id =
object_id(N'[dbo].[My_Table]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[My_Table]
GO
CREATE TABLE [dbo].[My_Table] (
[Products] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Distribution Center] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS
NULL ,
[Sales Amt] [float] NULL ,
[Time] [datetime] NULL ,
) ON [PRIMARY]
GO
sorry :->
"Omnibuzz" wrote:

> Hi Aviad,
> The create table script was having a syntax error. Fixed it.
> But here it seems to work fine in my machine :)
> try removing the distribution center column from the select and the group
by
> of the final query and try..
>|||I remember someone posting something like this...
the query analyzer was taking the next line of the comment as commented or
something similar.
I am not able to see what the problem might be :(
few last resorts..
If MY_TABLE is really your table then rename the column with an "_" in
between and try to get rid of this square brackets.
try it in a new QA window (Never knew I could get down to this level :)
use it as "DISTRIBUTION CENTER" instead of sq bracks..
"Aviad" wrote:
> Hi,
> Its not working here, somehow it doesn’t "recognize" the column:
> [TIMELEVELTABLE].[DISTRIBUTION CENTER] in the row:
> WHERE [TIMELEVELTABLE].[DISTRIBUTION CENTER] =
> [FORMULATIMELEVELTABLE].[DISTRIBUTION CENTER].
> Which in the calculated column.
> "Omnibuzz" wrote:
>

Calculated column in a table

Hi,
I have a table with a calculated column.
There is also a footer which calculates the sum in a column.
How I can calculate the sum from a caculated column?
Ex: 2 10
5 25 <- calculated column
--
7 35 <- calculated sum of column
(SRS 2000 SP2)
Thanks
EricThe best way to do this is to created a calculated field. On the field list,
do a right mouse click, add, click on calculated field. After that it is
treated like any other field.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"Eric" <jug@.nospam.nospam> wrote in message
news:uHCxZsEaFHA.1448@.TK2MSFTNGP09.phx.gbl...
> Hi,
> I have a table with a calculated column.
> There is also a footer which calculates the sum in a column.
> How I can calculate the sum from a caculated column?
>
> Ex: 2 10
> 5 25 <- calculated column
> --
> 7 35 <- calculated sum of column
> (SRS 2000 SP2)
>
> Thanks
> Eric
>|||Thanks for answering.
But now there's another problem.
I can't use an aggreate function in the column. The column calculates the
percentage of the first column to the Total.
Any idea jow I can do that in the report?
Thanks
Eric
"Bruce L-C [MVP]" <bruce_lcNOSPAM@.hotmail.com> schrieb im Newsbeitrag
news:eyqGY%23EaFHA.3712@.TK2MSFTNGP09.phx.gbl...
> The best way to do this is to created a calculated field. On the field
> list, do a right mouse click, add, click on calculated field. After that
> it is treated like any other field.
>
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "Eric" <jug@.nospam.nospam> wrote in message
> news:uHCxZsEaFHA.1448@.TK2MSFTNGP09.phx.gbl...
>> Hi,
>> I have a table with a calculated column.
>> There is also a footer which calculates the sum in a column.
>> How I can calculate the sum from a caculated column?
>>
>> Ex: 2 10
>> 5 25 <- calculated column
>> --
>> 7 35 <- calculated sum of column
>> (SRS 2000 SP2)
>>
>> Thanks
>> Eric
>|||Hi Eric,
What aggreate function? You may refer sample report Company Sales.rdl for
more information about how to sum the columns.
Sincerely yours,
Michael Cheng
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=====================================================
This posting is provided "AS IS" with no warranties, and confers no rights.|||Thanks for answering.
this is an too easy sample.
I have a column with values (DataBound). A second column should show the
percentage of first column to the sum.
Example:
20 20%
80 80%
-- --
100 100%
For calcualating the Second column I need to know the sum of the first
column.
How I do that?
If the second column is a 'calculated field', I can't use aggreate function
like 'Sum(column1)'.
thanks
Eric
"Michael Cheng [MSFT]" <v-mingqc@.online.microsoft.com> schrieb im
Newsbeitrag news:MDOIi7LbFHA.2476@.TK2MSFTNGXA01.phx.gbl...
> Hi Eric,
> What aggreate function? You may refer sample report Company Sales.rdl for
> more information about how to sum the columns.
>
> Sincerely yours,
> Michael Cheng
> Microsoft Online Partner Support
> When responding to posts, please "Reply to Group" via your newsreader so
> that others may learn and benefit from your issue.
> =====================================================> This posting is provided "AS IS" with no warranties, and confers no
> rights.
>|||Hi Eric,
Thanks for your patience.
For now, aggregates of aggregates are not currently supported in Reporting
Services so you will find other way to accomplish this. For example, you
could generate this data in the DataSet.\
Sincerely yours,
Michael Cheng
Microsoft Online Partner Support
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=====================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Calculate/create Row Number without identity

How do I output a row number for a table solely for the purpose of
querying for a unique row?

In my problem, the table from a legacy system does not have a primary
key, so it limits various querying I'd like to do that identifies
uniqueness in the table.

The problem is that since I'm using DTS to simply copy the table to
SQL, I don't want to create identity rows.chrispycrunch (chrispycrunch@.gmail.com) writes:
> How do I output a row number for a table solely for the purpose of
> querying for a unique row?
> In my problem, the table from a legacy system does not have a primary
> key, so it limits various querying I'd like to do that identifies
> uniqueness in the table.
> The problem is that since I'm using DTS to simply copy the table to
> SQL, I don't want to create identity rows.

Not sure why the use of DTS would preclude the use of an IDENTITY row,
but then again I have no experience of DTS. After all, IDENTITY seems
perfect in this case.

If there really is a problem for DTS, you make a two-stepper and have
DTS to park the data in a transient table, and insert from there into
the target table.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Hi. Are you sure that the original table has no duplicates? If there
are any
duplicate, you do not have unique rows. However, assuming you want to
establish an identity for future use, you could extract the old data
row-by-row
and set a unique identity of your own construction, and maintain that
with
any new rows that get added (and make sure to have a unique index on
that
value.
All in all, the identity column is made for this.
Joe Weinstein at BEA

Calculate Time Off

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), Wend
Sample data for tblTimeOff:-
10.00AM, 15, 0 - Timeoff period 10.00am to 10.15am on Wday
12.00pm, 60, 0 - Timeoff period 12.00pm to 1.00pm on Wday
15.00pm,15, 0 - - Timeoff period 3.00pm to 3.15pm on Wday
10.30AM, 15, 1 - Timeoff period 10.30am to 10.45am on Wend
12.30pm, 60, 1 - Timeoff period 12.30pm to 1.30pm on Wend
Saturday and Sunday are considered as Wend.
Mon - Fri are Wend
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 (wend) - 15
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), Wend
> Sample data for tblTimeOff:-
> 10.00AM, 15, 0 - Timeoff period 10.00am to 10.15am on Wday
> 12.00pm, 60, 0 - Timeoff period 12.00pm to 1.00pm on Wday
> 15.00pm,15, 0 - - Timeoff period 3.00pm to 3.15pm on Wday
> 10.30AM, 15, 1 - Timeoff period 10.30am to 10.45am on Wend
> 12.30pm, 60, 1 - Timeoff period 12.30pm to 1.30pm on Wend
> Saturday and Sunday are considered as Wend.
> Mon - Fri are Wend
> 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 (wend) - 15
> 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 difference

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

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)

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
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 values from a underlying table

I am building a customerlist within the customer sales of a period. I have a dataset with two tables: "customer" and "customer_ledger_entry".

In the report I will present the customer number, the customer name and the sales. The problem is the sales value is not available as a field, but I have to calculate this value from the "customer_ledger_entry" table. In this table are several entries (invoices, credit notes, etc.)

How to calculate the values from a underlying table?

Here is a post that may work. You would populate the sales value into a dictionary object and then reference it based on the key you decide to use.

(from my blog at http://sqlrs.blogspot.com)

One common problem in reporting and BI solutions is how to incorporate data from both an OLAP cube and relational tables. The UDM in SQL 2005 attempts to solve this, however it really means you still need to build the information into your cubes and dimension attributes.

What if you don't want to or can't?

Reporting Services provides a Custom Code tab within the Report Properties page. You can access various VB.NET objects and system assemblies, and reference external assemblies. One of the internal assemblies is the Dictionary object.

Steps to lookup values from a reference table in SQL:

Drag a list onto the report.
Drag a textbox into the list, or a field from the relational dataset. Modify the textbox to contain =Code.setValue(Fields!KeyField.Value, Fields!ValueField.Value)

Create another list below. Drag another textbox into the list. Modify the textbox expression to hard-code the key for now. =Code.getValue("MyKey")

In the Code Properties window, try the following:

public dict as new System.Collections.Generics.Dictionary(Of System, System)

function setValue(value as object, value2 as object) as object
dict.Add(value,value2)
return value
end function

function getValue(value as object) as object
return dict(value)
end function

Afterwards, you can hide the list box (or table or whatever) that loads the variable with the setValue function. The dictionary still gets populated.

If you have properly bound a table to the first list control, you should be able to lookup results in the second table.

This can be applied in many scenarios, including adding relational reference data to MDX results, and creating a relationship between two separate datasets.

I'd be interested to know if anyone uses this. It seems to have many different applications. One could possibly involve showing two sets of information, for things like variances or budget vs. actual data. If a value doesn't exist in the dictionary, the original field could be returned. If it does exist, the adjustment could be returned.

Note that Generics is .NET 2.0 - for 2000 you may need to use a different syntax but the concept is the same. Basically you're using a dictionary object (could be a hash table or whatever) to store a value by a key. Then you're looking up that value in a table (or list or whatever) to do further calculations.

cheers,

Andrew

|||

Selectis,

I believe you may want to create 2 dataset for your report, the first dataset for the "customer" and the second dataset for "customer_ledger_entry". You can then calculate your values like SUM(Fields!Sales.value,"customer_ledger_entry", customer name like =(Fields!FirstName,"customer")

I hope this was what you were looking for.

Ham

|||

I've made a the two datasets like you said. My expression is:

=Sum(Fields!Sales__LCY_.Value, "customer_ledger_entry"), (Fields!Customer_No_.Value, "customer_ledger_entry") like = (Fields!No_.Value, "customer")

When I run the report I get the message "The Value expression for the textbox refers to a the field "Customer_No_". Report item expressions can only refer to fields within the current data set scope or, if inside an aggregate, the specified data set scope.

|||

Selectis,

I must have misunderstood what you were trying to accomplish, I thought you when trying to display values from 2 different tables but I didn’t realize you want to reference the 2 datasets together.

If you can do the following:

You can nest data regions within other data regions. For example, if you want to create a sales record for each sales person in a database, you can create a list with text boxes and an image to display information about the employee, and then add table and chart data regions to show the employee's sales record.

I hope this helps

Ham

|||

I′ve found a way to calculate the value: I use one dataset with two tables: "customer" and "customer_ledger_entry".

The report contains a table and I've used the SUM function for the customer sales: =SUM(Fields!Sales.Value). Now my report calculates all the sales lines from the "customer_ledger_entry". That is not what I want. But the solution is to choose "Edit Group" for the detail line in your report. In the Group settings I added a sorting on the customer and I added a "Group on" expression. Now the SUM function only calculates the records for the customer listed on the line.

Calculate row size

Hello everybody:
How can I do to calculate the record size in bytes, and the table size in
bytes? Does exist any stored procedure to do that '
Thanks
Richard_SQLTable size:
EXEC sp_spaceused 'table_name'
For row size, you can average by the above result / SELECT COUNT(*) FROM
table_name
For individual rows, this gets a little trickier because there is overhead
for certain datatypes, and whether the data is nullable and/or is null.
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Richard_SQL" <Richard_SQL@.discussions.microsoft.com> wrote in message
news:ED295DB2-396D-4E5D-B42B-CAF858473F04@.microsoft.com...
> Hello everybody:
> How can I do to calculate the record size in bytes, and the table size in
> bytes? Does exist any stored procedure to do that '
> Thanks
> Richard_SQL|||Richard,
Be sure to use @.updateusage = 'TRUE' when invoking sp_spaceused.
Also, for more exact calculations concerning table and row size, see
"Estimating the Size of a Table" in SQL Server 2000 Books Online. There are
related topics for calculating table size for a heap table and a clustered
table.
Ron
--
Ron Talmage
SQL Server MVP
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:OSjvpDB9EHA.4004@.tk2msftngp13.phx.gbl...
> Table size:
> EXEC sp_spaceused 'table_name'
> For row size, you can average by the above result / SELECT COUNT(*) FROM
> table_name
> For individual rows, this gets a little trickier because there is overhead
> for certain datatypes, and whether the data is nullable and/or is null.
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>
>
> "Richard_SQL" <Richard_SQL@.discussions.microsoft.com> wrote in message
> news:ED295DB2-396D-4E5D-B42B-CAF858473F04@.microsoft.com...
> > Hello everybody:
> >
> > How can I do to calculate the record size in bytes, and the table size
in
> > bytes? Does exist any stored procedure to do that '
> >
> > Thanks
> >
> > Richard_SQL
>|||Thanks a lot for your help.
Richard
"Ron Talmage" wrote:
> Richard,
> Be sure to use @.updateusage = 'TRUE' when invoking sp_spaceused.
> Also, for more exact calculations concerning table and row size, see
> "Estimating the Size of a Table" in SQL Server 2000 Books Online. There are
> related topics for calculating table size for a heap table and a clustered
> table.
> Ron
> --
> Ron Talmage
> SQL Server MVP
>
> "Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
> news:OSjvpDB9EHA.4004@.tk2msftngp13.phx.gbl...
> > Table size:
> >
> > EXEC sp_spaceused 'table_name'
> >
> > For row size, you can average by the above result / SELECT COUNT(*) FROM
> > table_name
> >
> > For individual rows, this gets a little trickier because there is overhead
> > for certain datatypes, and whether the data is nullable and/or is null.
> >
> > --
> > http://www.aspfaq.com/
> > (Reverse address to reply.)
> >
> >
> >
> >
> > "Richard_SQL" <Richard_SQL@.discussions.microsoft.com> wrote in message
> > news:ED295DB2-396D-4E5D-B42B-CAF858473F04@.microsoft.com...
> > > Hello everybody:
> > >
> > > How can I do to calculate the record size in bytes, and the table size
> in
> > > bytes? Does exist any stored procedure to do that '
> > >
> > > Thanks
> > >
> > > Richard_SQL
> >
> >
>
>