【问题标题】:select rows based on value of column and distinct column根据列和不同列的值选择行
【发布时间】:2018-08-18 08:29:50
【问题描述】:

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

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 是什么?

【问题讨论】:

  • 不关心可能是糟糕设计的症状 - 你应该关心!

标签: mysql sql


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多