根据另一列,其中一列具有MAX值,为一列选择MAX值

时间:2013-12-11 17:41:57

标签: mysql case

我有一个表数据,来自不同的表格。我只想在第3栏有价值'债务' AND 1st column(DATE)具有最大值。最终值基于MAX(DATE)而非MAX(PRICE)。所以用简单的语言就是这样来的

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 THING中,它是我管理的数据库的一部分,它有这个查询并且现在想要在相同的结构上。致谢

1 个答案:

答案 0 :(得分: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