仅在使用CTE-SQL Server时显示唯一值

时间:2018-04-18 09:59:11

标签: sql sql-server tsql

我有以下查询:

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

正确连接字段并链接它们,但它现在正在创建重复项。我的结果集如下所示:

enter image description here

有没有办法在GTS_T中只显示唯一值?

谢谢

1 个答案:

答案 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