问题
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