为单个NAME从两个不同的行中选择两个值

时间:2013-12-07 12:36:18

标签: mysql

我想从表格中获取数据,其中有两个以上(至少2个是必须的)值是针对单个客户的,1)债务2)支付债务。我需要根据同一行中每个客户的最大日期显示这两个值。我正在使用下面的查询

QUERY

SELECT MAX(RECEIPTS.DATENEW) AS DATE,
   MAX(CASE WHEN PAYMENTS.PAYMENT = 'debt' THEN PAYMENTS.TOTAL END) `TAKEN DEBT`,
   MAX(CASE WHEN PAYMENTS.PAYMENT = 'debtpaid' THEN PAYMENTS.TOTAL END) `PAID DEBT`,
   CUSTOMERS.NAME 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 IN('debt', 'debtpaid')
GROUP BY RECEIPTS.ID

返回如下结果,似乎更接近......

enter image description here

但我需要债务和债务支付价值对于单个客户和他们的日期(个别日期)在同一行。所需数据类似于图像

enter image description here

1 个答案:

答案 0 :(得分:0)

嗯,这种方式起作用了! 只需注意一些事项,正如我所说,每个客户都有两个条目,因此必须由CUSTOMER进行分组并对日期应用相同的CASE子句,所以只需将代码放在有人可能会发现它有用的情况下。

SELECT
    MAX(CASE WHEN PAYMENTS.PAYMENT = 'debt' THEN PAYMENTS.TOTAL END) AS TAKENDEBT,
    MIN(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,
    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 CUSTOMER

感谢你的所有建议!