2009-07-21 97 views
2

我有一張桌子上有州,市,鎮和郵政編碼。郵政編碼有重複的數據,因爲一些郵政編碼有多個城鎮。現在我需要一個查詢來返回所有4列,但是我不想在結果中重複郵政編碼。我只想每個郵政編碼返回1條記錄。如果有多個城鎮,我想在結果記錄中返回「-----------」以表示多個城鎮。Distinct Values

我該怎麼做?

回答

2
SELECT CASE WHEN COUNT(Town) > 1 THEN '-----' ELSE MIN(Town) END AS Town, Zip 
FROM YourTable 
GROUP BY Zip 

編輯:,如果你也想返回其他領域,如國家,只需添加上如:

SELECT 
    CASE WHEN COUNT(Town) > 1 THEN '-----' ELSE MIN(Town) END AS Town, 
    CASE WHEN COUNT(Town) > 1 THEN '-----' ELSE MIN(State) END AS State, 
    Zip 
FROM YourTable 
GROUP BY Zip 
0

我假設郵政編碼只能與一個城市,州。

SELECT State 
, City 
, CASE WHEN MAX(Town) <> MIN(Town) THEN '-------' ELSE MAX(Town) END as Town 
, ZipCode 
FROM data 
GROUP BY State, City, ZipCode 

soomething like that?不知道它與其他選項有多高效。

編輯:我同意COUNT是一種更清晰的方式來表達這