如何从部分分组的Sqlite表中选择记录?

时间:2018-11-13 07:36:53

标签: sql sqlite group-by

我有一张这样的桌子。我想选择基于Fruits分组在一起的group_id,而不是VegetablesNuts。对于VegetableNuts,我都想要。

  group_id  name                type
    -----------------------------------
    1        Green Apple          Fruit 
    1        Red Apple            Fruit
    1        Blue Apple           Fruit
    2        Green Peas           Vegetable
    2        Snow Peas            Vegetable
    2        Another Pea          Vegetable
    3        Ground Nut           Nuts
    3        Peanut               Nuts
    4        Carrot               Vegetable

这就是我现在尝试过的方式。效果很好,但是我想知道是否有任何更简单的方法。

select * from Grocessaries GROUP BY group_id HAVING type in ('Fruit', 'Drinks')     

UNION all

select * from Grocessaries where type in ('Vegetable', 'Nuts') 

基本上,我想要这样的结果(将水果和所有蔬菜和坚果分组)

group_id  name                type
        -----------------------------------
        1        Green Apple          Fruit 
        2        Green Peas           Vegetable
        2        Snow Peas            Vegetable
        2        Another Pea          Vegetable
        3        Ground Nut           Nuts
        3        Peanut               Nuts
        4        Carrot               Vegetable

1 个答案:

答案 0 :(得分:1)

由于您是专门在用户界面中处理水果(和饮料)的,因此为它们返回的实际名称并不重要,因此您可以这样做

SELECT group_id,
  CASE type
    WHEN 'Fruits' THEN 'Fruits' -- or whatever you want to display
    WHEN 'Drinks' THEN 'Drinks'
    ELSE name
  END NameGrouped,
  type
FROM Grocessaries
GROUP BY group_id, NameGrouped, type