mysql - 根据列值和非重复列选择行

标签 mysql sql

我想根据店铺数量选择店铺位置不同的行,示例如下:

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;

DB-Fiddle.com Demo

关于mysql - 根据列值和非重复列选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906759/

相关文章:

mysql - 如何使用 mongify 将两个表合并为一个表

c# - ASP.Net-VB 到 .MDF 连接

php - MySQL 如果值为空则不搜索

mysql - 另一个 SQL 错误 1064 (42000) : cant locate the error

php - 将空白行插入表中以生成外键或更好的方法?

mysql - 从数据库中获取一行,从行中删除一个元素并将该行更新回数据库

php - 我应该在购买项目表中拥有产品的外键吗?

php - 我可以使用组连接的 2 种组合吗?或者我应该使用子查询

sql - 如何在代码优先迁移期间设置新表列的默认值?

mysql - 将列从父模型复制到子模型。好的做法还是坏的做法?