![](/img/trans.png)
[英]How to select distinct values from one column from on table and entire other table?
[英]In a table how to select distinct values of one column by keeping reference of other column?
在我的表中,我有 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
我認為您要求的類別只包含一個產品。 如果是這樣,您可以使用聚合:
select categoryid, max(productname) as productname
from t
group by categoryid;
您只需productname
group by categoryid
並獲得最小(或最大?) productname
:
select categoryid, min(productname) as productname
from tablename
group by categoryid
嘗試將 Row_number 與 partition 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.