简体   繁体   English

是否可以将数据透视/转换查询与另一个表结合起来(以添加额外的数据列)?

[英]Is it possible to combine a pivot/transform query with another table (to add an additional column of data)?

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. DATEHOUR将完全匹配,我可以从表中手动指定要使用名称/类型。

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.我尝试在FROM子句中对两个表进行INNER JOIN ,然后将列名添加到SELECT子句中,但它抱怨该字段名不是聚合 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.我还尝试将其添加到TRANSFORM子句(和PIVOT子句),但我认为您不能为它们指定多个字段。

Is this possible to do in a single query using SQL, or do I need to perform both queries separately?这可以在使用 SQL 的单个查询中完成,还是我需要分别执行两个查询?


One last note - the query still works after I INNER JOIN table T1 with T2 on the date/hour values (as it should).最后一点 - 在 I INNER JOINT1T2在日期/小时值上(应该如此)之后,查询仍然有效。 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?为什么不把它变成一个子查询并加入适当的 ID 呢?

eg,例如,

select a.*, b.extracolumn
from othertable b
join ( ... ) a
on a.ID = b.ID

You're getting the errors because of the group by in your above query.由于上述查询中的group by ,您会收到错误消息。 You shouldn't have the same problems if you join it, in its entirety, as a subquery.如果您将其全部作为子查询加入,则不应该遇到同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM