How do I (or can I) SELECT DISTINCT on multiple columns?

前端 未结 5 683
梦谈多话
梦谈多话 2020-11-21 23:53

I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day f

5条回答
  •  一向
    一向 (楼主)
    2020-11-22 00:04

    The problem with your query is that when using a GROUP BY clause (which you essentially do by using distinct) you can only use columns that you group by or aggregate functions. You cannot use the column id because there are potentially different values. In your case there is always only one value because of the HAVING clause, but most RDBMS are not smart enough to recognize that.

    This should work however (and doesn't need a join):

    UPDATE sales
    SET status='ACTIVE'
    WHERE id IN (
      SELECT MIN(id) FROM sales
      GROUP BY saleprice, saledate
      HAVING COUNT(id) = 1
    )
    

    You could also use MAX or AVG instead of MIN, it is only important to use a function that returns the value of the column if there is only one matching row.

提交回复
热议问题