我怎样才能删除null部分并在mysql中合并为一个?

时间:2017-04-14 14:06:47

标签: mysql

SELECT A_NAME,
ROUND(CASE
WHEN M_TYPE_CODE = 001
THEN AVG(A_PRICE)
END) AS A,
ROUND(CASE
WHEN M_TYPE_CODE = 002
THEN AVG(A_PRICE)
END) AS B
FROM PRICE
GROUP BY A_NAME, M_TYPE_CODE;

当我使用它时,结果是

A_NAME   ㅣ   A   ㅣ    B   ㅣ
Apple    ㅣ(null) ㅣ  3313  ㅣ
Apple    ㅣ 3000  ㅣ (null) ㅣ
Grape    ㅣ(null) ㅣ  5020  ㅣ
Grape    ㅣ 3140  ㅣ (null) ㅣ
...

所以我认为它会将A_NAME组合成一个,但是我会用null来两个不同的行,如何删除null并合并成一个?

another error

2 个答案:

答案 0 :(得分:0)

每个A_NAME有两行,因为该群组也使用了M_TYPE_CODE,但您没有在列列表中包含该列。试试这个:

SELECT A_NAME,
    AVG(IF(`M_TYPE_CODE` = '001',A_PRICE,NULL)) AS `A`,
    AVG(IF(`M_TYPE_CODE` = '002',A_PRICE,NULL)) AS `B`
FROM PRICE
GROUP BY A_NAME;

如果是语言设置问题,则没有后面的抽搐:

SELECT A_NAME,
    AVG(IF(M_TYPE_CODE = '001',A_PRICE,NULL)) AS A,
    AVG(IF(M_TYPE_CODE = '002',A_PRICE,NULL)) AS B
FROM PRICE
GROUP BY A_NAME;

答案 1 :(得分:-1)

不确定AVG和coalese是否会为您提供所需的结果。

SELECT A_NAME
     , ROUND(AVG(CASE WHEN M_TYPE_CODE = '001' THEN coalesce(A_PRICE,0) END)) AS A
     , ROUND(AVG(CASE WHEN M_TYPE_CODE = '002' THEN coalesce(A_PRICE,0) END)) AS B
FROM PRICE
GROUP BY A_NAME;

或者这可能取决于你想要实现的平均值。

SELECT A_NAME
     , ROUND(AVG(CASE WHEN M_TYPE_CODE = '001' THEN A_PRICE END)) AS A
     , ROUND(AVG(CASE WHEN M_TYPE_CODE = '002' THEN A_PRICE END)) AS B
FROM PRICE
GROUP BY A_NAME;