2016-12-15 75 views
0

我試圖從同一字段中選擇兩個不同的數據描述。數據通過同一個表中的類型和ID列進行區分。下面是我正在嘗試的查詢,但我得到重複的數據結果。附上兩張表的截圖和查詢結果Table and Results如何從同一字段中選擇包含不同數據的兩列

SELECT SEX,[ADDRESS],CITY,SOC_SEC_NUM,ZIP,ect... 

CASE WHEN CD.[TYPE] = 'COUNTY' 
THEN CD.[DESC] 
END AS COUNTY, 

--CASE WHEN CDTBL1.[TYPE] = 'ETH' 
--THEN CDTBL1.[DESC] 
--END AS ETH 

CDTBL1.[DESC] AS ETH 
--CD.[DESC] AS COUNTY 

--INTO #TMP 
FROM CDCLIENT 
INNER JOIN CDTBL1 
ON CDCLIENT.ETH_ID = CDTBL1.ID 
INNER JOIN CDTBL1 CD 
ON CAST(CDCLIENT.RES_COUNTY_ID AS VARCHAR) = CD.ID 

WHERE CDTBL1.[TYPE] = 'ETH' 
--AND CD.[DESC] IS NOT NULL 
--OR 
--CD.[TYPE] = 'COUNTY' 
ORDER BY LAST_NAME ASC 

--SELECT * FROM #TMP 
--WHERE COUNTY IS NOT NULL 

回答

1

我認爲問題是你有重複的ID。我會爲TYPE添加一些其他條件。

SELECT SEX,[ADDRESS],CITY,SOC_SEC_NUM,ZIP,ect... 

CASE WHEN CD.[TYPE] = 'COUNTY' 
THEN CD.[DESC] 
END AS COUNTY, 

--CASE WHEN CDTBL1.[TYPE] = 'ETH' 
--THEN CDTBL1.[DESC] 
--END AS ETH 

CDTBL1.[DESC] AS ETH 
--CD.[DESC] AS COUNTY 

--INTO #TMP 
FROM CDCLIENT 
INNER JOIN CDTBL1 
ON CDCLIENT.ETH_ID = CDTBL1.ID AND CDTBL1.TYPE = 'ETH' 
INNER JOIN CDTBL1 CD 
ON CAST(CDCLIENT.RES_COUNTY_ID AS VARCHAR) = CD.ID AND CD.TYPE = 'COUNTY' 

WHERE CDTBL1.[TYPE] = 'ETH' 
--AND CD.[DESC] IS NOT NULL 
--OR 
--CD.[TYPE] = 'COUNTY' 
ORDER BY LAST_NAME ASC 

--SELECT * FROM #TMP 
--WHERE COUNTY IS NOT NULL 
0

除了SQLChao響應,也可以取代你的初始SELECT通過SELECT DISTINCT,使用此選項刪除重複的結果。

相關問題