数据透视表省略具有Null值的行

时间:2014-10-22 20:52:34

标签: mysql pivot-table group-concat

我正在解决一个与this非常相似的问题,仅在我的情况下,我没有总结任何值。
我已经能够编写一个使用this page

解决方案的选择
SELECT 
  id, 
  GROUP_CONCAT(if(colID = 1, value, NULL)) AS 'First Name',
  GROUP_CONCAT(if(colID = 2, value, NULL)) AS 'Last Name',
  GROUP_CONCAT(if(colID = 3, value, NULL)) AS 'Job Title'
FROM tbl
GROUP BY id;

但是,我想省略value为空的行

2 个答案:

答案 0 :(得分:2)

如果源行的任何具有value IS NULL,我假设您要删除结果行。
您应该能够在HAVING子句中使用bit_and()实现该目标:

SELECT id
     , max(CASE WHEN colID = 1 THEN value END) AS fn
     , max(CASE WHEN colID = 2 THEN value END) AS ln
     , max(CASE WHEN colID = 3 THEN value END) AS jt
FROM   tbl 
GROUP  BY id
HAVING bit_and(value IS NOT NULL);

替代:

...
HAVING count(*) = count(value);

我没有在CASE语句中拼出ELSE NULL因为(per documentation):

  

如果没有匹配的结果值,则会返回ELSE之后的结果,如果没有NULL部分则返回ELSE

答案 1 :(得分:1)

只需将此约束添加到查询的where语句中,如下所示:

SELECT 
  id, 
  GROUP_CONCAT(if(colID = 1, value, NULL)) AS 'First Name',
  GROUP_CONCAT(if(colID = 2, value, NULL)) AS 'Last Name',
  GROUP_CONCAT(if(colID = 3, value, NULL)) AS 'Job Title'
FROM tbl
WHERE value IS NOT NULL
GROUP BY id;

修改

经过一些测试后,我可以找到一个合适的解决方案,但似乎有趣的是value is not null无法工作。

解决方案链接:http://sqlfiddle.com/#!2/b7a445/3

SELECT 
  id, 
  max(case when colID = 1 then value else '' end) AS fn,
  max(case when colID = 2 then value else '' end) AS ln,
  max(case when colID = 3 then value else '' end) AS jt
FROM tbl 
where not exists (select * from tbl b where tbl.id=b.id and value is null)
group by id