I have a relatively simple pivot/transform query, which appears as follows:
TRANSFORM Sum(T1.VALUE) As SumOfVal
SELECT T1.DATE, T1.HOUR
FROM T1
WHERE (T1.DATE = #1/1/2010#) AND
(T1.NAME IN ("name1", "name2")) AND
(T1.TYPE IN ("type1", "type2"))
GROUP BY T1.DATE, T1.HOUR
PIVOT T1.NAME + " " + T1.TYPE
Which returns me something like this:
DATE | HOUR | name1 type1 | name1 type2 | name2 type1 | name2 type2
------------------------------------------------------------------------
1/1/2010 | 1 | 222.22 | 123.11 | 1241.23 | 133124
1/1/2010 | 2 | 252.22 | 121.11 | 121.23 | 122150
And so on. Now, in another table (with a similar layout), I have more readings which I want to join to the end of the query as another column. The DATE and HOUR will match up exactly, and I can manually specifiy which name/type to use from the table.
Where I’m stuck is, how would I add this into the query? I tried to INNER JOIN the two tables in the FROM clause, and then added the column name to the SELECT clause, but it complained that the field name was not part of the aggregate function. I also tried to add it to the TRANSFORM clause (and the PIVOT clause), but I don’t think you can specify multiple fields for them.
Is this possible to do in a single query using SQL, or do I need to perform both queries separately?
One last note – the query still works after I INNER JOIN table T1 with T2 on the date/hour values (as it should). I just don’t know how to include the actual reading/value so it shows up in the result…
Why not just make this a subquery and join on the appropriate ID?
eg,
You’re getting the errors because of the
group byin your above query. You shouldn’t have the same problems if you join it, in its entirety, as a subquery.