Conditional grouping clause (sqlite)

巧了我就是萌 提交于 2020-01-05 08:52:14

问题


Inside a SELECT statement, is it possible to GROUP BY col_A if col_B = "some_value", otherwise GROUP BY col_C ? Then have that field that was used for grouping inside the results?

Like

SELECT value_of_the_column_used_for_group 
   FROM table WHERE ... 
   GROUP BY (IF col_B = "some_value" : col_A : ELSE : col_C)
   LIMIT 0, 20;

Basically I want to select children records that have distinct parents or parent records that have distinct IDs. But I want to select parent IDs, which can be the ID column or the "parent_ID" column from children records


回答1:


You, you can use a case statement:

SELECT (case when col_B = 'some_value' then col_A ELSE col_C end) 
FROM table WHERE ... 
GROUP BY (case when col_B = 'some_value' then col_A ELSE col_C end)
LIMIT 0, 20;



回答2:


You can add a name to your conditions and call after a while...

    SELECT (case when col_B = 'some_value' then col_A ELSE col_C end AS 'CONDITION')
    FROM table WHERE ...
    GROUP BY CONDITION
    LIMIT 0, 20;


来源:https://stackoverflow.com/questions/18471120/conditional-grouping-clause-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!