在表中如何通过保留另一列的引用来选择一列的不同值?

时间:2019-07-09 11:10:55

标签: mysql sql distinct where-clause

在我的表中,我具有CategoryID和ProductName,这里CategoryID具有重复的值。如何选择具有不同类别ID的产品名称?

我尝试了看起来类似的堆栈溢出答案,但是都没有帮助。

    +++++++++++++++  ++++++++++++++
    + ProductName +  + CategoryID +
    +++++++++++++++  ++++++++++++++
        Mac                1
        HP                 3
        Walker             1
        Bell               2
        Dell               4   
        Lenovo             3
        Pixel              2

结果应该是

    +++++++++++++++  ++++++++++++++
    + ProductName +  + CategoryID +
    +++++++++++++++  ++++++++++++++
        Mac                1
        HP                 3 
        Bell               2
        Dell               4   

3 个答案:

答案 0 :(得分:1)

尝试将Row_number与by一起使用。这是表格模式:

CREATE TABLE  docs (
  ProductName varchar(50) NOT NULL,
  CategoryID int  NOT NULL
) ;
INSERT INTO docs (ProductName ,CategoryID ) VALUES
  ('Mac', 1),
  ('HP', 3),
  ('Walker', 1 ),
  ('Bell', 2 ),
  ('Dell', 4 ),
  ('Lenova', 3),
  ('Pixel', 2)

然后使用foll运行。选择查询:

SELECT ProductName, CategoryID 
from(
SELECT CategoryID, ProductName, 
row_number() over (partition by CategoryID order by ProductName ) as rn
from docs ) tab
where rn = 1;

这将输出返回为

+++++++++++++++  ++++++++++++++
+ ProductName +  + CategoryID +
+++++++++++++++  ++++++++++++++
    Mac                1
    Bell               2
    HP                 3 
    Dell               4   

答案 1 :(得分:0)

我认为您要求的类别仅包含一个产品。如果是这样,您可以使用聚合:

select categoryid, max(productname) as productname
from t
group by categoryid
having count(*) = 1;

答案 2 :(得分:0)

您只需要group by categoryid并获得最小值(或最大值?)productname

select categoryid, min(productname) as productname
from tablename
group by categoryid