假设我在Ms Ms中有表,其中包含以下信息:
ColumnA ColumnB
1 abc
1 pqr
1 xyz
2 efg
2 hij
3 asd
我的问题是,如何将第二列中的值连接到基于第一列的行值。我想要的查询结果如下:
ColumnA ColumnB
1 abc, pqr, xyz
2 efg, hij
3 asd
我想通过查询来实现这一目标。有人可以帮助我实现这个目标吗?
答案 0 :(得分:21)
您需要一个功能来进行连接。
Microsoft Access condense multiple lines in a table
使用您的数据的示例:
Select T.ColumnA
, GetList("Select ColumnB From Table1 As T1 Where T1.ColumnA = " & [T].[ColumnA],"",", ") AS ColumnBItems
From Table1 AS T
Group By T.ColumnA;
答案 1 :(得分:7)
这是一个很好的链接:如何通过调用函数在SQL中执行此操作。说明非常清楚&该功能是为您编写的,因此您只需复制,粘贴和放大;走。即使是不了解VB的人也可以轻松实现它: Concatenate values from related records
答案 2 :(得分:2)
这可能很难获得。如果必须在查询而不是函数中执行,那么您将遇到的问题是可以连接到一列的行数限制。到目前为止,我发现实现这一目标的唯一方法是通过iif语句。
SELECT
test1.ColumnA AS ColumnA,
First([test1].[ColumnB]) & IIf(Count([test1].[ColumnB])>1,"," & Last([test1].[ColumnB])) AS ColumnB
FROM test1
GROUP BY test1.ColumnA;
返回:
ColumnA ColumnB
1 abc,xyz
2 efg,hij
3 asd
这将返回第一个和最后一个,但我确信只需一点工作就可以解决选择功能,但就像我说的那样你必须为你要添加的每个附加项添加更多的iif语句因此有限制。
答案 3 :(得分:1)
该表可以有一个序列列,它为ColumnA序列提供唯一的主键:
<html>
<body>
<?php
$to = “xyz@somedomain.com”;
$subject = “Contact Form”;
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$headers = “From: $email”;
$sent = mailto($to,$subject,$name,$message,$headers);
if($sent){
print('<a href=”contact.html”>Thank you. Click here to return to site.</a>')
}else{
print “There was an issue with your contact form”;
}
?>
</body>
</html>
可以创建一个交叉表:
table: t1
ColumnA sequence ColumnB
1 1 abc
1 2 pqr
1 3 xyz
2 1 efg
2 2 hij
3 1 asd
然后最终查询可以组合列并删除最后一个逗号:
query: x1
TRANSFORM Min([columnB] & ", ") AS Expr1
SELECT t1.columnA
FROM t1
GROUP BY t1.columnA
PIVOT t1.sequence;
columnA 1 2 3
1 abc, pqr, xyz,
2 efg, hij,
3 asd,
要自动填充序列,可以使用以下VBA代码:
SELECT x1.columnA, Left([1] & [2] & [3],Len([1] & [2] & [3])-2) AS columnB FROM x1;
columnA columnB
1 abc, pqr, xyz
2 efg, hij
3 asd