Why Oracle is saying not a GROUP BY expression?

后端 未结 4 1480
不知归路
不知归路 2020-12-21 15:58

I am Trying to retrive data from the Oracle database table with following conditions

  1. All entries found by zip-code should be grouped, sorted by zip-code desce
4条回答
  •  执念已碎
    2020-12-21 16:02

    The specific answer to your question is that uuid is not included in the group by expression. Other answers have already explained the MySQL (mis) feature that allows this to happen. Fixing the query is easy:

    SELECT ba.uuid AS uuid, COUNT(*) over() AS rowcount
    FROM basicaddress ba 
    WHERE ba.postalcode='143456' OR ba.lastname LIKE '%143456%' OR ba.city LIKE '%143456%'
    GROUP BY uuid,
            CASE WHEN ba.postalcode='143456' THEN ba.postalcode END 
    ORDER BY 
            max(CASE WHEN ba.postalcode='143456' THEN ba.postalcode END) DESC, 
            max(CASE WHEN ba.lastname LIKE '%143456%' THEN ba.lastname END) ASC, 
            max(CASE WHEN ba.city LIKE '%143456%' THEN ba.city ELSE ba.postalcode END)
    

    I also removed the "distinct" which should be redundant when using group by.

    That said, I don't see how this satisfies your original question. I would expect something more along the lines of the following:

    select (case when postalcode is not null then postalcode
                 when city is not null then city
                 when lastname is not null then lastname
            end),
           (case when postalcode is not null then 1
                 when city is not null then 2
                 when lastname is not null then 3
            end),
           count(*)
    from basicaddress ba
    group by (case when postalcode is not null then postalcode
                   when city is not null then city
                   when lastname is not null then lastname
              end),
             (case when postalcode is not null then 1
                 when city is not null then 2
                 when lastname is not null then 3
            end)
    order by 1, 2
    

    This may not be exactly what you need, but it should point you in the right direction. Also, this is standard SQL and will work in both databases.

提交回复
热议问题