如何从同一字段

时间:2016-12-15 18:33:37

标签: sql-server-2008 tsql

我试图从同一个字段中选择两个不同的数据描述。数据由同一表中的Type和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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

除了SQLChao回复之外,您还可以将SELECT替换为SELECT DISTINCT,使用此选项可以删除重复的结果。