我正在解决一个与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
为空的行
答案 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