Group By Except For Certain Value

后端 未结 4 837
清歌不尽
清歌不尽 2021-01-17 16:18

I\'m trying to create a (sqlite) query that will perform a GROUP BY but will not group anything with the value \'unknown\'. For example, I have the table:

i         


        
相关标签:
4条回答
  • 2021-01-17 16:49

    As a single query...

    SELECT
      MIN(id)            AS id,
      name,
      parent_id,
      school_id
    FROM
      yourTable
    GROUP BY
      CASE WHEN name = 'unknown' THEN id ELSE 0 END,
      name,
      parent_id,
      school_id
    

    Or possibly...

    GROUP BY
      CASE WHEN name <> 'unknown' THEN name ELSE CAST(id AS VARCHAR(???)) END,
      parent_id,
      school_id
    
    -- Where VARCHAR(???) is the data type of the `name` field.
    -- Also assumes no value in `name` is the same as an id for an 'unknown' field
    

    Both avoid UNION and the overhead of parsing the table twice, replacing it with a slightly increased complexity GROUP BY.

    0 讨论(0)
  • 2021-01-17 16:49
    SELECT  MIN(id), name, parent_id, school_id
      FROM  Table
    WHERE   name <> 'unknown'
    GROUP BY name, parent_id, school_id
    UNION ALL
    SELECT  id, name, parent_id, school_id
      FROM  Table
     WHERE  name = 'unknown'
    
    0 讨论(0)
  • 2021-01-17 16:52
    SELECT 
      MIN(id) AS id,
      IF(tmpname=id,"unknown",tmpname) AS name,
      parent_id,
      school_id
    FROM (
      SELECT 
        id,parent_id,school_id
        IF(name="unknown",id,name) AS tmpname
      FROM <tablename>
    ) AS baseview
    GROUP BY tmpname
    
    0 讨论(0)
  • 2021-01-17 17:00

    You can't easily do this with one statement but you can UNION the results of two statements

    • GROUP the list of all but unknown
    • Add (UNION) the list of all unknown

    SQL Statement

    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'
    

    Note that I assume you have posted wrong unknown id's in your result

    0 讨论(0)
提交回复
热议问题