2013-12-11 183 views
0

我有一個表格數據如下,來自不同的表格。如果第三列有「債務」值,並且第一個column(DATE)具有最大值,我想從第四列中獲取最大值。最終值基於MAX(DATE)而不是MAX(PRICE)。所以用簡單的語言來說就是這樣根據兩列其中一列有MAX值的其他兩列選擇MAX值

IF(MAX(DATE) && TYPE = 'debt'){ 
    MAX(PRICE); 
} 

這裏是可用數據的圖像視圖。

enter image description here

,我使用當前的查詢低於

SELECT 
    MAX(CASE WHEN PAYMENTS.PAYMENT = 'debt' AND RECEIPTS.DATENEW THEN PAYMENTS.TOTAL END) AS TAKENDEBT, 
    (CASE WHEN PAYMENTS.PAYMENT = 'debtpaid' THEN PAYMENTS.TOTAL END) AS GIVENDEBT, 
    MAX(CASE WHEN PAYMENTS.PAYMENT = 'debt' THEN RECEIPTS.DATENEW END) AS TAKENDATE, 
    MAX(CASE WHEN PAYMENTS.PAYMENT = 'debtpaid' THEN RECEIPTS.DATENEW END) AS GIVENDATE, 
    (MAX(CASE WHEN PAYMENTS.PAYMENT = 'debt' THEN PAYMENTS.TOTAL END) + SUM((CASE WHEN PAYMENTS.PAYMENT = 'debtpaid' THEN PAYMENTS.TOTAL END))) AS DUE,   
    CASE WHEN PAYMENTS.PAYMENT = 'debt' OR PAYMENTS.PAYMENT = 'debtpaid' THEN CUSTOMERS.NAME END AS CUSTOMER 
FROM RECEIPTS 
    INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID 
    INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT 
    INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID 
WHERE 
    (PAYMENTS.PAYMENT = 'debt' 
    OR PAYMENTS.PAYMENT = 'debtpaid') 
GROUP BY CUSTOMER 
ORDER BY DUE DESC 

這給了我與紅色的圓圈下面顯示的輸出,而我需要在綠圈的價值。這意味着它基於MAX(PRICE)獲得價值,而我需要基於MAX(DATE)和MAX(PRICE),因爲在同一日期可能有多個值。

enter image description here

請不要問我數據放在FIDDLE的事情,DATABASE它的一個爛攤子,我設法有這個疑問,現在要在同一結構。感謝

回答

0

嘗試類似的解決方案:

SELECT date, max(price) FROM yourTable 
    WHERE payment='debt' AND date = (SELECT max(date) From yourTable) 
    GROUP BY date 

SELECT date ,max(price) FROM yourTable 
    WHERE payment='debt' 
    GROUP BY date 
    ORDER BY date DESC 
    LIMIT 1 
+0

不在狀態使用子查詢,將是一個很大的混亂。正如我所說的想要以CASE語句的相同方式保持查詢的結構。 – Saqib