SQL ACCESS中的CONCAT

时间:2015-01-08 15:31:27

标签: sql ms-access

我有两张桌子:

TABLE_1
CODE    TYPE
A100    A
A100    B
A100    C
A200    A
A200    A

TABLE_2
CODE    DESCRIPTION
A100    XY
A200    ZH

我想加入两个表,结果如下:

CODE    DESCRIPTION TYPECONCAT
A100       XY        A, B, C
A200       ZH           A

第一列包含唯一代码,第二列包含通用描述,第三列连接第一个表的不同类型。 我尝试使用以下代码:

SELECT Distinct
Code,
Type,
Concat ("TypeConcat", “my_table”, "Code=""" & [Code] & """ and Type=""" & [Type] & """") AS TypeConcat
FROM my_table;

我不知道如何连接,使用&在这种情况下是运营商。

谢谢!

1 个答案:

答案 0 :(得分:0)

你走了。这里结合了几种技术,CONCAT并不能满足您的需求,但这样做会很好。

SELECT 'A100' AS [CODE], 'A' AS [TYPE] INTO #TABLE_1
INSERT into #TABLE_1 VALUES('A100','B')
INSERT into #TABLE_1 VALUES('A100','C')
INSERT into #TABLE_1 VALUES('A200','A')
INSERT into #TABLE_1 VALUES('A200','A')

SELECT 'A100' AS [CODE], 'XY' AS [DESCRIPTION] INTO #TABLE_2
INSERT into #TABLE_2 VALUES('A200','ZH')

SELECT DISTINCT t1.[CODE], t2.[DESCRIPTION], 
    (   SELECT STUFF((
            SELECT DISTINCT CAST(', ' AS VARCHAR(MAX)) + [Type]
            FROM #TABLE_1 t3
            WHERE t1.[CODE] = t3.[CODE]

            FOR XML PATH('')
        ),1,2,'') 
    ) AS [TYPECONCAT]
FROM    #TABLE_1 t1
JOIN    #TABLE_2 t2 ON t1.[CODE] = t2.[CODE]

DROP TABLE #TABLE_1
DROP TABLE #TABLE_2

主要有用的是FOR XML PATH命令,值得玩。

还应该使用codemonkeycaffeine,这是我使用的基本技术。

https://codemonkeycaffeine.wordpress.com/2013/08/21/sql-joining-rows-into-a-single-field/