小编典典

按某些值分组

sql

我正在尝试创建一个(sqlite)查询,该查询将执行GROUP BY,但不会将任何值’unknown’分组。例如,我有表:

id |   name  | parent_id | school_id |
 1 | john    |   1       |    1      |
 2 | john    |   1       |    1      |
 3 | john    |   1       |    1      |
 4 | nick    |   2       |    2      |
 5 | nick    |   2       |    2      |
 6 | nick    |   3       |    3      |
 7 | bob     |   4       |    4      |
 8 | unknown |   5       |    5      |
 9 | unknown |   5       |    5      |
 10| unknown |   5       |    5      |

使用正确的查询并带有“ GROUP BY名称,parent_id,school_id”,我需要返回以下行:

id |   name  | parent_id | school_id |
 1 | john    |   1       |    1      |
 3 | nick    |   2       |    2      |
 4 | nick    |   3       |    3      |
 5 | bob     |   4       |    4      |
 6 | unknown |   5       |    5      |
 7 | unknown |   5       |    5      |
 8 | unknown |   5       |    5      |

任何帮助将不胜感激。谢谢!


阅读 176

收藏
2021-04-07

共1个答案

小编典典

您很难用一个语句来完成此操作,但是可以UNION使用两个语句的结果

  • GROUP所有的名单 ,但 unknown
  • 添加(UNION)全部列表unknown

SQL语句

SELECT MIN(id), name, parent_id, school_id
FROM   YourTable
WHERE  name <> 'unknown'
GROUP BY
       name, parent_id, school_id
UNION ALL
SELECT id, name, parent_id, school_id
FROM   YourTable
WHERE  name = 'unknown'

请注意,我假设您unknown在结果中发布了错误的ID

2021-04-07