SQL一行但总共2行将每个值乘以设定值

时间:2018-04-25 18:29:38

标签: mysql sql database

您好我想通过将1值乘以200而另一行乘以50来获得总共2行。

我有一张像

这样的表格
=====================
ClubName | Type | Fee
=====================
Club1    |Adult | 1000
Club1    |Child | 500

我试图将1000乘以200而将500乘以50而不是添加它们,这就是我想要得到的总数。

我得到了一个成年人,但我怎么比去找孩子而不是加上他们?

SELECT Type, SUM(Fee * 200) AS MembershipFee
FROM fees
WHERE Clubname='hillcrest' AND Type='adult'

1 个答案:

答案 0 :(得分:1)

如果我理解正确,那么这应该有效:

SELECT Type, 
SUM(CASE WHEN Type = 'Adult' THEN Fee*200 
         WHEN Type = 'Child' THEN Fee*50 END) AS MembershipFee
 FROM yourTable
 WHERE Clubname='hillcrest'
 Group BY Type

如果您只想获得总和,可以执行以下操作。

SELECT Clubname, 
SUM(CASE WHEN Type = 'Adult' THEN Fee*200 
         WHEN Type = 'Child' THEN Fee*50 END) AS MembershipFee
FROM yourTable
WHERE Clubname='hillcrest'
Group BY Clubname