MySQL查询行为列

时间:2017-08-23 01:50:31

标签: mysql

我有一个类似下表的MySQL表。

Username | Region | Product
---------|--------|--------
Firdauss | CRO | DMC
Firdauss | ECO | DMC
Firdauss | EMO | DMC
Firdauss | NRO | DMC
Firdauss | SRO | DMC

目前我的查询结果如下表

Product | CRO      | ECO       | EMO       | NRO       | SRO 
--------|-----     |-----      |-----      |-----      |----
DMC     | Firdauss | 0         | 0         | 0         | 0
DMC     | 0        | Firdauss  | 0         | 0         | 0
DMC     | 0        | 0         | Firdauss  | 0         | 0
DMC     | 0        | 0         | 0         | Firdauss  | 0
DMC     | 0        | 0         | 0         | 0         | Firdauss 

我的查询是

 select _PRODUCT,
 if(_REGION = 'CRO',concat(USR_FIRSTNAME," ",USR_LASTNAME," 
 (",DEP_TITLE,")"),0) as CRO
 ,if(_REGION = 'ECO',concat(USR_FIRSTNAME," ",USR_LASTNAME," 
 (",DEP_TITLE,")"), 0) as ECO
 ,if(_REGION = 'NRO',concat(USR_FIRSTNAME," ",USR_LASTNAME," 
 (",DEP_TITLE,")"), 0) as NRO
 ,if(_REGION = 'SRO',concat(USR_FIRSTNAME," ",USR_LASTNAME," 
 (",DEP_TITLE,")"), 0) as SRO
 ,if(_REGION = 'EMO',concat(USR_FIRSTNAME," ",USR_LASTNAME," 
 (",DEP_TITLE,")"), 0) as EMO
 from t1 order by _PRODUCT asc ;

我想要得到的就像下面的表格

Product | CRO      | ECO      | EMO      | NRO      | SRO 
--------|-----     |-----     |-----     |-----     |----
DMC     | Firdauss | Firdauss | Firdauss | Firdauss | Firdauss

愿任何人帮助我吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

汇总产品列:

SELECT
    _PRODUCT,
    MAX(CASE WHEN _REGION = 'CRO'
             THEN CONCAT(USR_FIRSTNAME, ' ', USR_LASTNAME, '(', DEP_TITLE, ')') END) CRO,
    MAX(CASE WHEN _REGION = 'ECO'
             THEN CONCAT(USR_FIRSTNAME, ' ', USR_LASTNAME, '(', DEP_TITLE, ')') END) ECO,
    MAX(CASE WHEN _REGION = 'NRO'
             THEN CONCAT(USR_FIRSTNAME, ' ', USR_LASTNAME, '(', DEP_TITLE, ')') END) NRO,
    MAX(CASE WHEN _REGION = 'SRO'
             THEN CONCAT(USR_FIRSTNAME, ' ', USR_LASTNAME, '(', DEP_TITLE, ')') END) SRO,
    MAX(CASE WHEN _REGION = 'EMO'
             THEN CONCAT(USR_FIRSTNAME, ' ', USR_LASTNAME, '(', DEP_TITLE, ')') END) EMO
FROM t1
GROUP BY _PRODUCT
ORDER BY _PRODUCT