我有两张桌子:
和
我需要得到这样的东西:
HeaderID | Position1 | IsSuccessful | Position2 | IsSuccessful
-------------------------------------------------------------------------
24719 | gold_box | true | propname25 | false
24720 | beyond | false | wtv | false
24721 | red_box | false | wtv22 | true
我到目前为止管理了这个:
TRANSFORM Max(Proposals.PropName) AS MaxOfPropName
SELECT Headers.HeaderID
FROM Headers INNER JOIN Proposals ON Headers.ProposalID = Proposals.ProposalID
GROUP BY Headers.HeaderID
PIVOT Headers.Position;
HeaderID | Position1 | Position2 |
------------------------------------------
24719 | gold_box | propname25 |
24720 | beyond | wtv |
24721 | red_box | wtv22 |
现在我想从数据透视表中进行选择,但它无法正常工作,并且无法在网上找到任何相关文档,例如:
select * from (
TRANSFORM Max(Proposals.PropName) AS MaxOfPropName
SELECT Headers.HeaderID
FROM Headers INNER JOIN Proposals ON Headers.ProposalID = Proposals.ProposalID
GROUP BY Headers.HeaderID
PIVOT Headers.Position;
)
有没有办法在另一个选择查询(ms访问)中使用数据透视表的结果?如何? 之后我将不得不使用7个表格的单个查询,并使用额外的3个数据透视表加入它们...... :)我很抱歉这个问题的人,但是我被困了< / p>
谢谢
答案 0 :(得分:1)
考虑将带有两个内部联接的派生表子查询添加到每个Position的已保存交叉表查询中。如果存在更多位置,则添加更多子查询。
CrossTab 查询(另存为以下主查询中使用的单独查询)
TRANSFORM Max(Proposals.PropName) AS MaxOfPropName
SELECT Headers.HeaderID
FROM Headers
INNER JOIN Proposals ON Headers.ProposalID = Proposals.ProposalID
GROUP BY Headers.HeaderID
PIVOT Headers.Position
主要查询
SELECT crosstabQ.HeaderID, crosstabQ.Position1, pos1.IsSuccessful,
crosstabQ.Position2, pos2.IsSuccessful
FROM (crosstabQ
INNER JOIN
(SELECT IsSuccessful
FROM Headers
WHERE Position = 1) AS pos1
ON pos1.HeaderID = crosstabQ.HeaderID)
INNER JOIN
(SELECT IsSuccessful
FROM Headers
WHERE Position = 2) AS pos2
ON crosstabQ.HeaderID = pos2.HeaderID
或者,运行条件聚合,它是数据透视查询的通用版本(这里布尔值将返回整数,0或-1):
SELECT Headers.HeaderID,
Max(IIF(Headers.Position=1, Proposals.PropName, NULL)) As Position1,
Max(IIF(Headers.Position=1, Headers.IsSuccessful, NULL)) As IsSuccessful1,
Max(IIF(Headers.Position=2, Proposals.PropName, NULL)) As Position2,
Max(IIF(Headers.Position=2, Headers.IsSuccessful, NULL)) As IsSuccessful2
FROM Headers
INNER JOIN Proposals ON Headers.ProposalID = Proposals.ProposalID
GROUP BY Headers.HeaderID