将类似的值分组到新的select语句中

时间:2013-02-10 22:08:48

标签: mysql sql

我有一张看起来像这样的桌子......

supplier_name  status       count 
supplier_a     Unavailable  1
supplier_a     Refunded     5
supplier_a     Shipped      10
supplier_z     Refunded     2
supplier_z     Shipped      4

我确切地知道我想要哪些列,并且我想使用第一个表中的值来返回如下结构的值......

supplier_name   unavailable   refunded   shipped
supplier_a      1             5          10
supplier_z      0             2          4

(注意:如果特定列没有值,则应将其设置为0)

这可以在查询中实现吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
   supplier_name,
   SUM(COALESCE(CASE WHEN status = 'unavailable' THEN  `count` END, 0)) unavailable,
   SUM(COALESCE(CASE WHEN status = 'refunded' THEN  `count` END, 0)) refunded,
   SUM(COALESCE(CASE WHEN status = 'shipped' THEN  `count` END, 0)) shipped
FROM tbl
GROUP BY supplier_name 

<强> SQL FIDDLE DEMO

答案 1 :(得分:1)

我认为这样的事情应该有效:

SELECT Supplier_Name, 
  MAX(CASE WHEN STATUS = 'Unavailable' THEN Count ELSE 0 END) as Unavailable,
  MAX(CASE WHEN STATUS = 'Refunded' THEN Count ELSE 0 END) as refunded,
  MAX(CASE WHEN STATUS = 'Shipped' THEN Count ELSE 0 END) as shipped
FROM YourTable
GROUP BY Supplier_Name

这是SQL Fiddle

祝你好运。