如何使SELECT合并重复的主键

时间:2016-09-07 15:54:15

标签: mysql sql select group-by sum

我正在执行一个如下所示的查询:

SELECT a.transactionID,a.customerID,b.value      
        FROM adjustments a 
                INNER JOIN change b 
                        on  a.transactionID = b.transactionID 
                        and a.event_date    = b.event_date 
                        and a.event_id      = b.event_id 
        WHERE comment LIKE 'TRANSFER'
        ORDER BY a.transactionID;

此查询带来以下结果:

    transactionID | customerID | value
   ------------------------------------     
    TRANSFER-001  |    CUSTA   | -200
    TRANSFER-001  |    CUSTB   |  200
    TRANSFER-002  |    CUSTC   | -150
    TRANSFER-002  |    CUSTD   |   0
    TRANSFER-003  |    CUSTA   |   0
    TRANSFER-003  |    CUSTC   |  150

我需要更改此查询以显示一个列表,该列表忽略同一value的{​​{1}}总和为 0 的情况,并对{{{{1}进行分组1}}和值如下:

transactionID

你能就如何解决这个问题提出任何建议吗?

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * FROM (
SELECT a.transactionID,a.customerID,b.value      
    FROM adjustments a 
    INNER JOIN change b 
                    on  a.transactionID = b.transactionID 
                    and a.event_date    = b.event_date 
                    and a.event_id      = b.event_id 
    WHERE comment LIKE 'TRANSFER'
)M
GROUP BY transactionID,customerID,value
HAVING SUM(value) <> 0
ORDER BY transactionID;

答案 1 :(得分:1)

SELECT distinct a.transactionID,a.customerID,b.value      
    FROM adjustments a 
            INNER JOIN change b 
                    on  a.transactionID = b.transactionID 
                    and a.event_date    = b.event_date 
                    and a.event_id      = b.event_id 
    WHERE comment LIKE 'TRANSFER'
    ORDER BY a.transactionID;

在开头尝试使用distinct,它将消除所有重复值。

答案 2 :(得分:1)

如果我理解正确,您需要条件聚合。但是,您需要转移客户,并且没有用于执行此操作的列。您可以使用变量枚举每个事务的客户,并使用它来转移事务中的前两个客户:

SELECT transactionId,
       MAX(CASE WHEN seqnum = 1 THEN customerId END) as customer_A,
       MAX(CASE WHEN seqnum = 1 THEN value END) as value_A,
       MAX(CASE WHEN seqnum = 2 THEN customerId END) as customer_B,
       MAX(CASE WHEN seqnum = 2 THEN value END) as value_B
FROM (SELECT a.transactionID, a.customerID, b.value,
             (@rn := if(@t = a.transactionID, @rn + 1,
                        if(@t := a.transactionID, 1, 1)
                       )
             ) as seqnum
      FROM adjustments a INNER JOIN
           change c 
           ON a.transactionID = c.transactionID AND
              a.event_date    = c.event_date AND
              a.event_id      = c.event_id CROSS JOIN
           (SELECT @rn := 0, @t := '') params,
      WHERE comment LIKE 'TRANSFER'
      ORDER BY a.transactionID, b.value DESC
     ) t
GROUP BY transactionId
HAVING SUM(value) <> 0;