我有以下查询:
with GTS_cte AS
(SELECT distinct [BusinessTermID], GTS_T =
STUFF ((SELECT ', ' + dbo.TblField.GTS_table
FROM dbo.TblField
WHERE [BusinessTermID] = Y.[BusinessTermID] AND dbo.TblField.GTS_table <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.Tblfield AS Y
GROUP BY [BusinessTermID])
,
syn_cte as (
SELECT [BusinessTermID], syns = STUFF
((SELECT ', ' + dbo.TblBusinessSynonym.Synonym
FROM dbo.TblBusinessSynonym
WHERE [BusinessTermID] = x.[BusinessTermID] AND dbo.TblBusinessSynonym.Synonym <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.TblBusinessSynonym AS x
GROUP BY [BusinessTermID])
select syn_cte.BusinessTermID, syn_cte.syns, GTS_cte.GTS_T
from syn_cte join
GTS_cte on GTS_cte.BusinessTermID = syn_cte.BusinessTermID
正确连接字段并链接它们,但它现在正在创建重复项。我的结果集如下所示:
有没有办法在GTS_T中只显示唯一值?
谢谢
答案 0 :(得分:2)
在 DISTINCT
中使用 Sub-Query
。
试试这个:
;with GTS_cte AS
(SELECT [BusinessTermID], GTS_T =
STUFF ((SELECT DISTINCT ', ' + dbo.TblField.GTS_table
FROM dbo.TblField
WHERE [BusinessTermID] = Y.[BusinessTermID] AND dbo.TblField.GTS_table <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.Tblfield AS Y
GROUP BY [BusinessTermID])
,
syn_cte as (
SELECT [BusinessTermID], syns = STUFF
((SELECT DISTINCT ', ' + dbo.TblBusinessSynonym.Synonym
FROM dbo.TblBusinessSynonym
WHERE [BusinessTermID] = x.[BusinessTermID] AND dbo.TblBusinessSynonym.Synonym <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.TblBusinessSynonym AS x
GROUP BY [BusinessTermID])
select syn_cte.BusinessTermID, syn_cte.syns, GTS_cte.GTS_T
from syn_cte join
GTS_cte on GTS_cte.BusinessTermID = syn_cte.BusinessTermID