我在Accecss 2007中有两张表格。
Town Table
----------
TownName | FlatCount | DetachedCount | SemiCount
A | 5 | 3 | 4
B | 2 | 6 | 3
Cost Table
----------
Prop | PCost
Flat | 10
Detached | 20
Semi | 30
我希望通过将Town表中的Count与Cost表中相应的PCost相乘得到如下输出。公寓FlatCost = Town.FlatCount * Cost.PCost
。
Results
-------
Town | FlatCount | FlatCost | DetachedCount | DetachedCost | .....
A | 5 | 50 | 3 | 60 |
B | 2 | 20 | 6 | 120 |
我试图通过使用IIF来做到这一点,但不确定如何在IIF子句中为每种属性类型获取PCost。
由于
答案 0 :(得分:4)
看起来你正在混合数据和元数据,例如表Flat
中的数据值Cost
成为表FlatCount
中的元数据值(列名称)Town
。这不是一个好主意,可能就是为什么你在写一个简单的查询时遇到困难。
重新构建Town
表格,使其包含TownName
,Prop
和PCount
列。请记住,最糟糕的SQL DML是由错误SQL DDL;)
答案 1 :(得分:3)
您可以使用子查询来检索项目的成本:
select TownName
, FlatCount
, FlatCount * (select PCost from Cost where Prop = 'Flat') as FlatCost
, DetachedCount
, DetachedCount * (select PCost from Cost where Prop = 'Detached')
as DetachedCost
, ...
from Town
答案 2 :(得分:1)
您必须交叉加入表格。然后,为了获得好的值,将PCost置于乘法中,否则放入0。
然后,您可以使用Group by:
执行SUMSELECT t.Town,
t.FlatCount,
SUM(t.FlatCount * IIF(c.Prop = 'Flat', c.PCost, 0)) AS FlatCost,
t.DetachedCount,
SUM(t.DetachedCount * IIF(c.Prop = 'Detached', c.PCost, 0)) AS DetachedCost,
FROM Town t, Cost c
GROUP BY t.Town, t.FlatCount, t.DetachedCount