2

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

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)

这可以在查询中实现吗?

4

2 回答 2

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 小提琴演示

于 2013-02-10T22:15:01.750 回答
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

祝你好运。

于 2013-02-10T22:18:23.077 回答