简体   繁体   English

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

[英]Pivot Table Omitting Rows that Have Null values

I am solving a problem very similar to this only in my case, I am not summing any values. 我仅在我的情况下解决与这个问题非常相似的问题,我没有对任何值求和。
I have been able to write a select that works using solution from 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;

However, I want to omit rows that have the value to be null 但是,我想省略具有空value

I assume you want to drop the result row if any of the source rows has value IS NULL . 我假设你要删除的结果行,如果任何一个源行具有value IS NULL
You should be able to achieve that with bit_and() in the HAVING clause: 您应该能够在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);

Alternative: 选择:

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

I didn't spell out ELSE NULL in the CASE statements because ( per documentation ): 我没有在CASE语句中拼出ELSE NULL ,因为( 根据文档 ):

If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part. 如果没有匹配的结果值,则返回ELSE之后的结果;如果没有ELSE部分,则返回NULL

Just add this constraint to the where statement of your query, like this: 只需将此约束添加到查询的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;

EDIT 编辑

After some tests I could make a solution to work, but it seems interesting why value is not null won't work. 经过一些测试,我可以提出一个解决方案,但是为什么value is not null似乎value is not null ,这似乎很有趣。

Solution link: http://sqlfiddle.com/#!2/b7a445/3 解决方案链接: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM