如何在Database中为值创建单独的列

时间:2015-07-07 11:21:25

标签: mysql sql mysql-workbench multiple-columns

我有一个SQL查询,显示数据库中不同表的信息。其中一个字段称为PieceType,它包含PLT,CASE,CTN等值。每个公司可以有不同数量的PieceType,例如公司4可能只有PLT,但公司5可能有10种不同类型。我想在不同的列中显示这些类型,如:

Plt | CASE | CTN

我的SQL查询:

SELECT  c.Name,
        jp.PieceType
FROM customer c
LEFT JOIN job_new jn ON ja.JobID = jn.ID
LEFT JOIN job_pieces jp ON ja.JobID = jp.ID
WHERE c.Company_ID = compid
GROUP BY c.ID

现在查询只显示PieceTypes中的一个值,即使该公司可能有多个片段类型。我尝试了GROUP_CONCAT(DISTINCT jp.PieceType),但显示了同一列中的所有值。我需要将每件作品放在一个单独的栏目中。 样本数据库可以在sqlfiddle上找到:http://www.sqlfiddle.com/#!9/c34306/3

2 个答案:

答案 0 :(得分:0)

您可以选择在哪里查找所需的属性。

即:

Select 
name,
(select property from job_pieces where companyid = id and property = 'A') as A,
(select property from job_pieces where companyid = id and property = 'B') as B,
(select property from job_pieces where companyid = id and property = 'C') as C
 from company

答案 1 :(得分:0)

我认为你正在寻找PIVOT TABLE。希望这有效:

SET group_concat_max_len=4294967294;
SET @COLUMNS = NULL;

/* Build columns to pivot */

SELECT GROUP_CONCAT(
        DISTINCT CONCAT(
            'CASE WHEN jp.PieceType = "', 
            jp.PieceType ,
            '" THEN 1 ELSE NULL END AS ',
            jp.PieceType
        )
) INTO @COLUMNS
FROM job_pieces jp;

/* Build full query */
SET @SQL = CONCAT(
        'SELECT  
                c.Name,
                ',@COLUMNS,'
        FROM customer c
        LEFT JOIN job_new jn ON ja.JobID = jn.ID
        LEFT JOIN job_pieces jp ON ja.JobID = jp.ID
        WHERE c.Company_ID = compid
        GROUP BY c.ID'
);

/* Prepare and execute the query*/
PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;