很抱歉提前提出了含糊的问题。
我有下表:
State Sales
AL 1000
AK 2000
MI 4000
MA 3000
PA 1500
WY 3000
NY 2000
VM 1000
现在每个州属于一个或多个区域:
Regions
AB: AL, 50%AK
CD: 50%Ak, MI
EF: MA, PA, 25%WY
GH: 75%WY, NY, VM
我想要下表:
State Region Sales
AL AB 1000
AK AB 1000
AK CD 1000
MI CD 4000
MA EF 3000
PA EF 1500
WY EF 750
WY GH 2250
NY GH 2000
VM GH 1000
我有一些 SQL 经验,但我不知道如何继续。有什么指点吗?
最佳答案
删除了我之前的答案,您的架构是正确的,但是您应该在区域表上添加数据(或将其重命名为另一个表名称,当该表被命名为区域时会很困惑),如下所示:
region_code state_code percentage
AB AL 100
AB AK 50
CD Ak 50
CD MI 100
EF MA 100
EF PA 100
EF WY 25
GH WY 75
GH NY 100
GH VM 100
那么您的查询将类似于:
SELECT State.code, Region.code, ((Region.percentage * State.sales) / 100) as Sales
FROM State
INNER JOIN Region
ON State.code = Region.state_code
NOTE: this answer is made to have a small changes on your schema. This answer serve as an example or to give you an idea. I suggest you analyze more on how your database schema should be made. Normalizing database and Proper naming of tables should be done if needed
关于mysql - 如何根据表中选择的百分比将行值分配给不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764549/