简体   繁体   English

将两个 Access 表中的值相乘

[英]Multiplying values from two Access tables

I have two tables as below in Accecss 2007.我在 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

I would like to get an output like below by multiplying the Count from the Town table with the corresponding PCost in the Cost table.我想通过将 Town 表中的 Count 与 Cost 表中的相应 Pcost 相乘来获得如下所示的 output。 FlatCost = Town.FlatCount * Cost.PCost for a flat. FlatCost = Town.FlatCount * Cost.PCost为一个单位。

Results
-------
Town | FlatCount | FlatCost | DetachedCount | DetachedCost | .....
A    | 5         | 50       | 3             | 60           |
B    | 2         | 20       | 6             | 120          |

I have tried to do this by using IIF, but not sure how to get PCost for each property type within the IIF clause.我试图通过使用 IIF 来做到这一点,但不确定如何为 IIF 子句中的每个属性类型获取 Pcost。

Thanks谢谢

Looks like you are mixing data and meta data eg the data value Flat in table Cost becomes metadata value (column name) FlatCount in table Town .看起来您正在混合数据和元数据,例如表Cost中的数据值Flat变为表Town中的元数据值(列名) FlatCount This is not a good idea and is probably why you are having difficulties writing what should be a simply query.这不是一个好主意,这可能就是为什么您在编写应该是一个简单的查询时遇到困难的原因。

Restructure your Town table so that it has columns TownName , Prop and PCount .重组您的Town表,使其包含TownNamePropPCount列。 And remember that most bad SQL DML is caused by bad SQL DDL ;)请记住,最糟糕的 SQL DML 是由糟糕的SQL DDL引起的;)

You could use a subquery to retrieve the cost of an item:您可以使用子查询来检索项目的成本:

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

You have to cross join the tables.你必须交叉加入表格。 Then, for good values, put PCost in the multiplication, else, put 0.然后,对于好的值,将 PCost 放入乘法中,否则,放入 0。

You can then do a SUM using a Group by:然后,您可以通过以下方式使用 Group 进行 SUM:

SELECT 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

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

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