Select unique rows, according to value in a secondary column

感情迁移 提交于 2019-12-10 19:19:54

问题


I have a simple mysql table:

id, code, product_name, supplier
 1, 3844, ProductName1, Supplier1
 2, 3844, ProductName1, Supplier2
 3, 1233, ProductName2, Supplier2

I want to query all distinct products from table. So sql code is select * from table group by code.

My problem:

I want to set supplier priority in "group by" statement (e.g. Supplier1 is most relevant, but can be absent in list for a given code). Products #1 and #2 are the same. In my resulting table I want to see:

id, code, product_name, supplier
 1, 3844, ProductName1, Supplier1
 3, 1233, ProductName2, Supplier2

How can I accomplish this?


回答1:


You probably need this:

SELECT
  MIN(id) id,
  code,
  MIN(product_name) product_name,
  MIN(supplier) supplier
FROM
  yourtable
WHERE
  (code, CASE WHEN supplier='Supplier1' THEN '' ELSE supplier END)
  IN (SELECT   code, min(CASE WHEN supplier='Supplier1' THEN '' ELSE supplier END)
      FROM     yourtable
      GROUP BY code)
GROUP BY
  code
ORDER BY
  min(id);

Please see fiddle here.




回答2:


Try this one,

SELECT * FROM table_name    GROUP BY code    ORDER BY supplier


来源:https://stackoverflow.com/questions/15518415/select-unique-rows-according-to-value-in-a-secondary-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!