【问题标题】:Summing up values of Some rows and add it to Value of other rows总结一些行的值并将其添加到其他行的值
【发布时间】:2021-11-25 13:45:41
【问题描述】:
我需要您在 SQL 查询中的帮助,在下面给出的示例表中,我只需要两行没有将必需标志设置为 Y 的行。这两行的值应具有 (Price * % Levied) + ((Price)*(% Levied) 的所需标志设置为 Y 的行的总和)
| Name |
Price |
% Levied |
Required |
| King Bed |
10000 |
120 |
|
| Queen Bed |
24000 |
140 |
|
| Delivery |
240 |
140 |
Y |
| Porter Charges |
20 |
20 |
Y |
我的结果应该是这样的
| Name |
Values |
| King Bed |
(10000 * 120)+(240 * 140)+(20 * 20) |
| Queen Bed |
(24000 * 140)+(240 * 140)+(20 * 20) |
我什至不知道从哪里开始。让我知道是否需要任何信息。提前致谢。
【问题讨论】:
标签:
mysql
sql
relational-database
【解决方案1】:
SELECT t1.Name, t1.Price * t1.Levied + t3.CommonPayment Values
FROM table t1
CROSS JOIN ( SELECT SUM(t2.Price * t2.Levied) CommonPayment
FROM table t2
WHERE t2.Required = 'Y' ) t3
WHERE t1.Required <> 'Y'
【解决方案2】:
试试这样的
with required_rows as
(
select Price * '% Levied' as 'add_on_price'
from my_table
where Required = 'Y'
),
sum_required_rows as
(
select sum (add_on_price) as total_add_on_price
from required_rows
),
select Name,
Price,
% Levied,
((Price * '% Levied') + total_add_on_price) as final_price
from my_table
inner join sum_required_rows on 1=1
where Required != 'Y'