我有一个表格如下。我需要构建一个查询来查找以下内容。
( FeeComponentValue Sum
的 where feeComponentCalc = 1
) - ( FeeComponentValue Sum
的 where feeComponentCalc = 1
) 应该是 group by feeSettingId
请帮忙
CREATE TABLE `feevalues` (
`feevaluesId` int(11) NOT NULL,
`feeSettingId` int(11) NOT NULL,
`feeComponentId` int(11) NOT NULL,
`feeComponentValue` int(11) DEFAULT NULL,
`feeComponentCalc` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
--转储表feevalues
的数据
INSERT INTO `feevalues`
(`feevaluesId`, `feeSettingId`, `feeComponentId`, `feeComponentValue`, `feeComponentCalc`)
VALUES
(27, 29, 1, 1000, 1),
(28, 29, 12, 2000, 1),
(29, 29, 3, 3000, 1),
(30, 29, 4, 4000, 1),
(103, 30, 3, 1000, 1),
(104, 30, 1, 2000, 1),
(105, 30, 3, 3000, 1),
(106, 30, 1, 4000, 1),
(107, 30, 14, 5000, 2),
(108, 30, 2, 6000, 2),
(109, 30, 13, 7000, 2),
(110, 30, 2, 8000, 2),
(111, 31, 1, 1000, 1),
(112, 31, 3, 2000, 1),
(113, 31, 13, 4000, 2),
(114, 31, 2, 3000, 2),
(122, 32, 1, 1, 1),
(123, 32, 3, 3, 1),
(124, 32, 4, 4, 1),
(125, 32, 2, 5, 2),
(126, 32, 14, 6, 2),
(127, 32, 13, 7, 2);
--
最佳答案
我假设您的意思是在第二种情况下...其中 FeeComponentCalc = 2...
,对吗?
使用条件聚合:
select
feeSettingId,
sum(case feeComponentCalc when 1 then feeComponentValue else 0 end) -
sum(case feeComponentCalc when 2 then feeComponentValue else 0 end) as result
from feevalues
group by feeSettingId
请参阅demo .
或者:
select
feeSettingId,
sum(
case feeComponentCalc
when 1 then feeComponentValue
when 2 then -feeComponentValue
else 0
end
) as result
from feevalues
group by feeSettingId
请参阅demo .
结果:
| feeSettingId | result |
| ------------ | ------ |
| 29 | 10000 |
| 30 | -16000 |
| 31 | -4000 |
| 32 | -10 |
关于mysql - 一个字段的值基于另一个字段的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58276192/