Oracle SQL GROUP BY “not a GROUP BY expression” help

后端 未结 3 1420
庸人自扰
庸人自扰 2020-12-30 04:16

I have a table some_table like

+--------+----------+---------------------+-------+
| id     | other_id | date_value          | value |
+--------         


        
相关标签:
3条回答
  • 2020-12-30 04:35

    You cannot SELECT any column that is not either an aggregate or computed from only the columns used in the GROUP BY clause.

    However there are three ways to do it:

    • You can use analytic functions

      SELECT id, other_id, date_value, value
        FROM ( SELECT id, other_id, date_value, MAX(date_value) OVER (partition by other_id) max_date, value
                 FROM some_table )
       WHERE max_date = date_value;
      
    • You can use a self join with a “greater than ” clause and detect your max this way

      SELECT t1.id, t1.other_id, t1.date_value, t1.value
        FROM some_table t1
        LEFT OUTER JOIN some_table t2
                     ON ( t1.other_id = t2.other_id AND t2.date_value > t1.date_value )
       WHERE t2.other_id IS NULL
      
    • You can use a subquery

        WITH max AS ( SELECT other_id, MAX(date_value) FROM some_table GROUP BY other_id )
      SELECT id, other_id, date_value, value
        FROM some_table
       WHERE ( other_id, date_value ) IN ( SELECT * FROM max )
      
    0 讨论(0)
  • 2020-12-30 04:41

    Probably this is the simplest way

    SELECT id, other_id, date_value, value
    FROM some_table
    WHERE date_value in (SELECT MAX(date_value)
                         from some_table
                         GROUP BY other_id
                         HAVING other_id in (1,2,3));
    

    Test the above query here

    0 讨论(0)
  • 2020-12-30 04:47
     select id, other_id, date_value, value from
     (
       SELECT id, other_id, date_value, value, 
       ROW_NUMBER() OVER (partition by other_id order BY Date_Value desc) r
       FROM some_table 
       WHERE other_id IN (1, 2, 3) 
     )
     where r = 1
    
    0 讨论(0)
提交回复
热议问题