在 table 中如何通过保持对另一列的引用来 select 一列的不同值?

In a table how to select distinct values of one column by keeping reference of other column?

在我的 table 中,我有 CategoryID 和 ProductName,这里的 CategoryID 有重复的值。我如何 select ProductName 具有不同的 categoryID?

我尝试过看起来相似的堆栈溢出答案,但 none 有帮助。

    +++++++++++++++  ++++++++++++++
    + 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   

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

select categoryid, max(productname) as productname
from t
group by categoryid;

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

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

尝试使用 Row_number 和分区依据。这是 Table 架构:

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查询:

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

这returns输出为

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