【问题标题】:How do I select records from Sqlite table partially grouped?如何从部分分组的 Sqlite 表中选择记录?
【发布时间】:2018-11-13 07:36:52
【问题描述】:

我有一张这样的桌子。我想选择基于group_id 而不是VegetablesNuts 组合在一起的Fruits。对于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

【问题讨论】:

  • 你能详细说明一下逻辑吗?为什么蓝苹果和红苹果被过滤掉了,而雪豆却留在了你想要的输出中?
  • 在第一个查询中 GROUP BY group_id 毫无意义,因为您没有使用任何聚合函数..
  • 您似乎在混合分组和排序
  • 订单对我来说不是问题。我已经从查询中删除了订购部分。我只关心分组部分。
  • 为什么是Green Apple Fruit 而不是Red Apple FruitBlue Apple Fruit

标签: sql sqlite group-by


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多