以下MySQL查询结果集重复MerchantID

select MerchantID,Category,SUM(Amount)
group by MerchantID,Category
from merchants

这将产生以下结果:
MerchantID | Category | Total |

1           | gold     | 450  |
1           | silver   | 600  |
2           | gold     | 1120 |
2           | bronze   | 200  |

我想得到如下结果集:
MerchantID | gold | silver | bronze |

1           | 450  | 600    | 0      |
2           | 1120 | 0      | 200    |

我试了很多问题,但没有得到这样的结果。请为我的问题提供一个解决方案。谢谢。

最佳答案

使用条件聚合:

select MerchantID,
       SUM(CASE WHEN Category = 'gold' THEN Total ELSE 0 END) AS gold,
       SUM(CASE WHEN Category = 'silver' THEN Total ELSE 0 END) AS silver,
       SUM(CASE WHEN Category = 'bronze' THEN Total ELSE 0 END) AS bronze
from merchants
group by MerchantID

Demo here

关于mysql - MySQL如何将第二组参数结果转换为列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31322908/

10-12 01:21