在Access数据库中组合单个表的行中的部分匹配

时间:2014-08-22 17:47:38

标签: sql access-vba ms-access-2010

我的表格如下所示:

Product   1       2      3       4       5        6      7       8       9
005778  110023  112623  117273  4371    4377    50563           
070370  110023  112623  1930    40007   4216    4310    4318    4428    56257
010702  110023  112623  2392    40007                   
012702  110023  112623  2392    40007                   
017965  110023  112623  2392    40007                   
017966  110023  112623  2392    40007                   
034350  110023  112623  2622    40007   56257               
024940  110023  112623  2622    40007   56257               
071300  110023  112623  40007   4215    4216    4218    4321    56257   
071330  110023  112623  40007   4215    4216    4218    4321    56257   

我希望它看起来像这样:

Product                         1          2      3      4       5        6      7       8       9
005778                        110023    112623  117273  4371    4377    50563           
070370                        110023    112623  1930    40007   4216    4310    4318    4428    56257
010702/012702/017965/017966   110023    112623  2392    40007                   
034350/024940                 110023    112623  2622    40007   56257               
071300/071330                 110023    112623  40007   4215    4216    4218    4321    56257   

我试图使用Allen Browne的ConcatRelated()但没有成功。我试图将这些数据合并到Access 2010报告中使用。 VBA或SQL解决方案将不胜感激。

2 个答案:

答案 0 :(得分:0)

在SQL2005或更高版本中,您可以尝试类似:

select products, t.*
from ( select distinct [1],[2],[3],[4],[5],[6],[7],[8],[9] from tbl ) t
    cross apply (select products = stuff(
        (select '/' + product from tbl z 
         where z.[1] = t.[1] AND z.[2] = t.[2] ... AND z.[9] = t.[9] 
         for xml path(''))   --concat list
       , 1,1,'') ) z         --remove first '/'

如果它们可以为空,则需要isnull(z.[1],'') = isnull(t.[1],'')等。

答案 1 :(得分:0)

一种方法是在表中添加一个Calculated字段,将字段[1]到[9]连接成一个字符串,即

Field Name: ValuesString
Expression: "|" & [1] & "|" & [2] & "|" & [3] & "|" & [4] & "|" & [5] & "|" & [6] & "|" & [7] & "|" & [8] & "|" & [9] & "|"
Result Type: Text

然后您可以像{<1}}那样使用

ConcatRelated()

返回

SELECT 
    Max(ConcatRelated("Product","YourTable","ValuesString=""" & [ValuesString] & """","","/")) AS ProductList, 
    Max(YourTable.[1]) AS MaxOf1, 
    Max(YourTable.[2]) AS MaxOf2, 
    Max(YourTable.[3]) AS MaxOf3, 
    Max(YourTable.[4]) AS MaxOf4, 
    Max(YourTable.[5]) AS MaxOf5, 
    Max(YourTable.[6]) AS MaxOf6, 
    Max(YourTable.[7]) AS MaxOf7, 
    Max(YourTable.[8]) AS MaxOf8, 
    Max(YourTable.[9]) AS MaxOf9
FROM YourTable
GROUP BY YourTable.ValuesString;