我想根据店铺数量选择店铺位置不同的行,示例如下:
id | item_name | number_of_store| store_location|
+----+---------+-------------------+-------------+
| 3 | margarine | 2 | QLD |
| 4 | margarine | 2 | NSW |
| 5 | wine | 3 | QLD |
| 6 | wine | 3 | NSW |
| 7 | wine | 3 | NSW |
| 8 | laptop | 1 | QLD |
+----+---------+-------------------+-------------+
想要的结果如下图所示:
id | item_name | number_of_store| store_location|
+----+---------+-------------------+-------------+
| 3 | margarine | 2 | QLD |
| 4 | margarine | 2 | NSW |
| 5 | wine | 3 | QLD |
| 6 | wine | 3 | NSW |
| 8 | laptop | 1 | QLD |
+----+---------+-------------------+-------------+
我不关心返回哪个 id 列值。所需的 SQL 是什么?
最佳答案
您可以使用GROUP BY
:
SELECT id, item_name ,number_of_store, store_location
FROM tab
GROUP BY item_name ,number_of_store, store_location;
-- will work if ONLY_FULL_GROUP_BY is disabled
否则你需要ANY_VALUE
或类似 MIN
的聚合函数:
SELECT ANY_VALUE(id) AS id, item_name ,number_of_store, store_location
FROM tab
GROUP BY item_name ,number_of_store, store_location;
关于mysql - 根据列值和非重复列选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906759/