Sunday, February 19, 2012

Cross tab stored procedure

Hi
I have a table with rows of timestamped values for given variables. Each of the variables are periodically inserted at the same time. ie
DateTime Variable Value.
T1 V1 xxxx
T1 V2 xxxx
T1 V3 xxxx
T2 V1 yyyy
T2 V2 yyyy
T2 V3 yyyy
In a SQLserver stored procedure I would like to insert this data into a temp table like the following. I don't need summaries just need a table or query where I can select on a variables value. ie "select * from temptable where V3 = yyyy"
Datetime V1 V2 V3
T1 xxxx xxxx xxxx
T2 yyyy yyyy yyyy
any suggestions for an SQL statement.
thanks in advance.
I don't exactly understand your business requirements. Are V1, V2, and V3 the only possible values for the Variable column? If so, something like this might help to get you started:

SELECT
DateTime,
MIN(V1),
MIN(V2),
MIN(V3)
FROM
(
SELECT
DateTime,
CASE
WHEN Variable = 'V1' THEN Value ELSE NULL
END AS V1,
CASE
WHEN Variable = 'V2' THEN Value ELSE NULL
END AS V2,
CASE
WHEN Variable = 'V3' THEN Value ELSE NULL
END AS V3
FROM
yourTable
) AS subQuery
GROUP BY
DateTime


|||

Thanks Terri

The base table contains many variables. The data in this table is produced by a periodic time base event which inserts a row for each of the variables along with their current value. What I am trying to achieve is a record set where I can compare the values of selected variables in a single row based on the timestamp. ie
DateTime Var1 Var2 Var3
1/1/2005 10:00 Product1 10 20
1/1/2005 10:05 Product2 9 15
1/1/2005 10:10 Product2 12 30
1/1/2005 10:20 Product1 15 16
Once I have this record set I can then do selections based on the value of any variable ie
"select * from recorset where Var1 = 'Product1'"
I tried a statement similar to the one you have posted but my case statement sintax wasn't quite right.
I'm not in the office for a few days so may not get a chance try your code.
regards
Noel

No comments:

Post a Comment