Select

如何使用 SELECT DISTINCT

  • January 15, 2019

我有一個關於在 SQL 中使用 DISTINCT 關鍵字的問題。我有一個名為客戶的表。每條記錄包含 3 個欄位:CustID、CustName、CustCity。5 條記錄顯示了“芝加哥”的 CustCity。

我希望 SQL 結果只顯示每個唯一城市名稱的一條記錄。另外,我只想查看每條記錄中的 CustID 和 CustName。

我試過了,但出現語法錯誤:

SELECT CustID, CustName DISTINCT CustCity 
FROM Customers

MS-Access 缺少視窗函式,因此您需要一個子查詢解決方案。我認為這會起作用:

SELECT c.* 
FROM Customers AS c
 INNER JOIN
   ( SELECT CustCity, MIN(CustID) AS CustID
     FROM Customers
     GROUP BY CustCity
   ) AS m
 ON (  m.CustCity = c.CustCity
   AND m.CustID = c.CustID
    ) ;
select t.* from 
(
   select custId,custName,CustCity,row_number() over (partition by custcity order by custcity) r from customers
) t
where r=1

引用自:https://dba.stackexchange.com/questions/161713