在组内按组选择总和

时间:2018-04-28 13:06:21

标签: mysql mysqli

使用此示例iformation表:

enter image description here

如何输出此信息?

enter image description here

我正在尝试此查询, 但它只是给了我一个' PART'的总数。每个' NAMES'。

的行
SELECT
    NAMES
  , SUM(PART = "F001") AS SUM_F001
  , SUM(PART = "F002") AS SUM_F002
  , SUM(PART = "F003") AS SUM_F003
FROM
  MY_TABLE
GROUP BY NAMES ASC 

2 个答案:

答案 0 :(得分:2)

您与当前查询非常接近。
但您需要使用下面的查询来正确转动。

SELECT 
    NAMES
  , MAX(CASE WHEN PART = 'F001' THEN QTY ELSE 0 END) AS F001
  , MAX(CASE WHEN PART = 'F002' THEN QTY ELSE 0 END) AS F002
  , MAX(CASE WHEN PART = 'F003' THEN QTY ELSE 0 END) AS F003
  , SUM(QTY) AS alias
FROM 
 FROM
  MY_TABLE
GROUP BY
  NAMES # Don't use ASC OR DESC on GROUP BY because it's deprecated
ORDER BY
 NAMES ASC 

答案 1 :(得分:0)

你可以使用如下查询

{{1}}