SQL: Is it possible to 'group by' according to 'like' function's results?

前端 未结 5 1401
暖寄归人
暖寄归人 2021-02-20 13:44

I am using Oracle SQL and I want to group some different rows that \'like\' function results. To elaborate with an example:


Let\'s assume I have a table MESA w

相关标签:
5条回答
  • 2021-02-20 14:26

    Another variant of David Markle answer:

    SELECT 
      fruit_name,
      count(1)  as fruit_count
    FROM (
      SELECT 
        CASE 
          WHEN m.str LIKE '%APPLE%' THEN 'Apple'
          WHEN m.str LIKE '%ORANGE%' THEN 'Orange' 
        END                                         as fruit_name
      FROM 
        MESA m
      WHERE 
        m.str LIKE '%FRUIT%'
        AND 
        (m.str LIKE '%APPLE%' OR m.str LIKE '%ORANGE%')
    )
    GROUP BY 
      fruit_name  
    

    Same thing, but only 1 CASE required, which simplifies support ...

    0 讨论(0)
  • 2021-02-20 14:32

    Sure:

    WITH Fruits AS (
        SELECT 
            CASE 
               WHEN m.str LIKE '%APPLE%' THEN 'Apple'
               WHEN m.str LIKE '%ORANGE%' THEN 'Orange' 
            END AS FruitType           
        FROM MESA m
        WHERE m.str LIKE '%FRUIT%')
    SELECT FruitType, COUNT(*) 
    FROM Fruits
    WHERE FruitType IN ('Apple', 'Orange')
    GROUP BY FruitType;
    
    0 讨论(0)
  • 2021-02-20 14:33

    I would do it this way -- only requires a single change to add additional types of fruit.

    WITH fruits AS (
      SELECT 'APPLE' fruit FROM DUAL
      UNION ALL
      SELECT 'ORANGE' fruit FROM DUAL
    )
    SELECT fruit, count(*)
    FROM MESA m, fruits
    WHERE m.str LIKE '%FRUIT%'
    AND m.str LIKE '%' || fruits.fruit || '%'
    GROUP BY fruit
    

    If your strings are reliably in the format you showed in your sample data, I would consider changing the predicate to one condition, WHERE m.str LIKE 'FRUIT%' || fruits.fruit ||'%'.

    0 讨论(0)
  • 2021-02-20 14:34

    Something like this?

    SELECT Fruit,
          SUM(counter)
     FROM ( SELECT CASE 
                       WHEN m.str LIKE '%APPLE%'
                           THEN 'APPLE'
                       ELSE 'ORANGE'
                   END AS Fruit
                   COUNT(*) AS counter
              FROM MESA m 
             WHERE m.str LIKE '%FRUIT%' 
               AND (m.str LIKE '%APPLE%' OR m.str LIKE '%ORANGE%')
             GROUP BY m.str
          )
    GROUP BY Fruit
    
    0 讨论(0)
  • 2021-02-20 14:43
    SELECT count(*) AS 'Apples'
    FROM MESA m
    WHERE m.str LIKE '%FRUIT%'
    AND m.str LIKE '%APPLE%'
    
    SELECT count(*) AS 'Oranges'
    FROM MESA m
    WHERE m.str LIKE '%FRUIT%'
    AND m.str LIKE '%ORANGE%'
    

    Would that work?

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