2015-04-24 43 views
0

我有一個包含services for invoices的mysql表。mysql查詢中的條件求和值

它看起來像

servicename|ammount|price|tag(type of service)|discount(service worthy of discount, true or false)|clientDiscount(client worthy of discount, true or false)

我需要做一個查詢,groups by yearsums(amount * price)

但是,如果discountclientDiscounttrue我需要計算的discount of 15%

我已經嘗試與案件和if statements但沒有任何工作。我真的不知道女巫的結局如何開始。而且說實話,我不能真正掌握案件和言論是如何運作的。我認爲我需要製作一個包含服務的Sum,其中包含折扣true和客戶折扣true,然後是包含服務而沒有折扣的另一個總額並添加這些upp以獲得正確的總和?現在它就像我頭上的一個螞蟻農場。

+0

提供一些示例數據和預期輸出。 –

回答

0

你可以聚合它沒有ifdiscountclientdiscount是整數,因此您可以簡單地將其與折扣百分比相乘。 @pala稍微修改的腳本:

select year(invoicedate), sum(amount * price * (1 - discount * clientdiscount * 0.15)) total 
    from invoices 
    group by year(invoicedate); 
+0

它的工作原理。但我不知道爲什麼?你能否解釋 – Jesper

+0

由於相關性,'1 - 折扣* clientdiscount * 0.15'在'discount'或'clientdiscount'爲0時變爲'1-0',如果它們都是'1'則爲'1 - 0.15'。 –

+0

@Jesper這是簡單的算術。值*(1-0.15)=值* 0.85。折扣和客戶折扣可能等於0或1.當兩者都等於1時,您必須申請折扣。當一個(或兩個)爲0時,您不必應用折扣。因此,在第一種情況下,您將獲得值*(1 - 1 * 1 * 0。15)=值* 0.85。在第二種情況下 - 值*(1 - 0 * 0.15)=值* 1 =值。 –

1

你想這樣的:

select year(invoicedate), sum(amount * price * if(discount and clientdiscount, 0.85, 1)) total 
    from invoices 
    group by year(invoicedate); 

demo here

if聲明是這樣工作的。 if(condition, value-if-true, value-if-false)。因此,在您的示例中,如果discount and clientdiscount爲真(即它們都是1),它將返回折扣額15%(折扣X與乘以1 - X相同)。如果條件爲假,它將返回1,這將不會修改amount * price的結果。綜上所述,if被處理之後,sum變成之一:
sum(amount * price * 0.85) -- if discount and client discount are both 1
OR
sum(amount * price * 1) -- if discount and client discount are both 0

+0

可能是一個愚蠢的問題,但在我的折扣中,clientDiscount列中的值是true和false不是1或0.它很容易改變。但它可以像真實或錯誤的價值一樣工作嗎? – Jesper

+0

它應該可以正常工作。 –

+0

我愛你!!!!!!!我快到了。我做了兩個字段「總數」和「總數」,是否有可能將這兩個總和(total - totaldiscount)作爲最終的總和?這裏是我現在在哪裏的鏈接。 http://sqlfiddle.com/#!9/ee57c/2/0我收到一個錯誤,說現在有總計。 – Jesper