我希望使用mysql在使用多个条件的单个查询中使用sum和substarct函数创建查询
在上表中,我想求和其中的我希望使用mysql在使用多个条件的单个查询中使用sum和substarct函数创建查询,mysql,Mysql,在上表中,我想求和其中的ledgertype='Earning',并在其中减去 ledgertype='reduction'并显示这两个值。。。。。如何编写查询 提前感谢…您可以使用此功能实现。因为您还想打印收入和扣除额,所以我使用了子查询 select sum_earnings , sum_deduction , sum_earnings - sum_deduction from ( select sum(case when ledgertype = 'Earning' then ledge
ledgertype='Earning'
,并在其中减去
ledgertype='reduction'
并显示这两个值。。。。。如何编写查询
提前感谢…您可以使用此功能实现。因为您还想打印收入和扣除额,所以我使用了子查询
select sum_earnings , sum_deduction , sum_earnings - sum_deduction
from ( select sum(case when ledgertype = 'Earning' then ledgervalue end) sum_earrnings, sum(case when ledgertype = 'Deductions' then ledgervalue end) as sum(sum_deduction)
from ratecard ) a
我无法理解“两种值”,但您可以通过以下方式获得两种类型的聚合:
Select SUM(ledgerValue), ledgerType FROM ratecard group by ledgerType
如果您想要一个运行总数,您可以使用一个变量来计算
DROP TABLE IF EXISTS T;
CREATE TABLE T (ID INT,AMOUNT INT, TYP VARCHAR(10));
INSERT INTO T VALUES
(1,12500,'Earnings'),(2,3200,'Earnings'),(3,1200,'Earnings'),
(4,1200,'Deductions'),(5,200,'Deductions'),(6,600,'Deductions'),(7,500,'Deductions'),
(8,12000,'Earnings'),(9,3200,'Deductions');
select t.*,
if(t.`typ` = 'Earnings' ,@rt:=@rt+amount,@rt:=@rt-amount) RunningTotal
from t
,(select @rt:=0) rt;
order by t.id
+------+--------+------------+--------------+
| ID | AMOUNT | TYP | RunningTotal |
+------+--------+------------+--------------+
| 1 | 12500 | Earnings | 12500 |
| 2 | 3200 | Earnings | 15700 |
| 3 | 1200 | Earnings | 16900 |
| 4 | 1200 | Deductions | 15700 |
| 5 | 200 | Deductions | 15500 |
| 6 | 600 | Deductions | 14900 |
| 7 | 500 | Deductions | 14400 |
| 8 | 12000 | Earnings | 26400 |
| 9 | 3200 | Deductions | 23200 |
+------+--------+------------+--------------+
9 rows in set (0.00 sec)
你在追求一个总价值吗?所有收入-所有扣除额?请参阅,虽然此代码可以回答问题,但提供有关如何和/或为什么解决问题的其他上下文将提高答案的长期价值。基于此url获取查询并删除此查询中的限制
DROP TABLE IF EXISTS T;
CREATE TABLE T (ID INT,AMOUNT INT, TYP VARCHAR(10));
INSERT INTO T VALUES
(1,12500,'Earnings'),(2,3200,'Earnings'),(3,1200,'Earnings'),
(4,1200,'Deductions'),(5,200,'Deductions'),(6,600,'Deductions'),(7,500,'Deductions'),
(8,12000,'Earnings'),(9,3200,'Deductions');
select t.*,
if(t.`typ` = 'Earnings' ,@rt:=@rt+amount,@rt:=@rt-amount) RunningTotal
from t
,(select @rt:=0) rt;
order by t.id
+------+--------+------------+--------------+
| ID | AMOUNT | TYP | RunningTotal |
+------+--------+------------+--------------+
| 1 | 12500 | Earnings | 12500 |
| 2 | 3200 | Earnings | 15700 |
| 3 | 1200 | Earnings | 16900 |
| 4 | 1200 | Deductions | 15700 |
| 5 | 200 | Deductions | 15500 |
| 6 | 600 | Deductions | 14900 |
| 7 | 500 | Deductions | 14400 |
| 8 | 12000 | Earnings | 26400 |
| 9 | 3200 | Deductions | 23200 |
+------+--------+------------+--------------+
9 rows in set (0.00 sec)