在上述表我要總結多個條件使用單個查詢總和和substarct函數創建查詢,其中ledgertype='Earning'
和其中。減去 ledgertype='Deduction'
並顯示這兩個值.....如何寫查詢?
在此先感謝...
在上述表我要總結多個條件使用單個查詢總和和substarct函數創建查詢,其中ledgertype='Earning'
和其中。減去 ledgertype='Deduction'
並顯示這兩個值.....如何寫查詢?
在此先感謝...
您可以使用它來實現。由於您想打印收入和扣減,所以我使用了子查詢。
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
@Deepak工作? –
我無法理解「兩個值」,但你可以得到兩種類型的總結:
Select SUM(ledgerValue), ledgerType FROM ratecard group by ledgerType
SELECT (SUM_VAL - SUBSTRACT_VAL) as balance FROM
(
select sum(ledgerValue) AS SUM_VAL FROM ratecard WHERE ledgerType ='Earning',
select sum(ledgerValue) AS SUBSTRACT_VAL FROM ratecard WHERE ledgerType = 'substract'
) t1
儘管此代碼可能會回答問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文可以提高答案的長期價值。 –
基於此網址獲取查詢並刪除此查詢中的限制https://forums.mysql.com/read.php?10105508,105543#msg-105543 –
如果你想運行總,你可以使用一個變量來計算。
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:[email protected]+amount,@rt:[email protected]) 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)
您是否已經完成了一個總價值?所有收入 - 所有扣除額? – alejandrogiron
請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry