如何将多列与逗号分隔符组合?

时间:2011-05-20 18:08:58

标签: ms-access

我有11列作为Note1,Note2,Note3,...... Note11。我写了这样的查询来组合

SELECT DormData.BuildingID, 
        DormData.DormRoomID, 
        DormData.Item, 
        DormData.Result, 
        DormData.InspectorID, 
        DormData.Date, 
        DormData.Qty, 
        DormData.Section, 
        (Note1 & " , " 
            & Note2 & ",  " 
            & Note3 & " , " 
            & Note4 & " , " 
            & Note5 & " ,  " 
            & Note6 & " , " 
            & Note7 & ", " 
            & Note8 & ", " 
            & Note9 & ", " 
            & Note10 & ", " 
            & Note11) AS Notes, 
        DormData.Comments, 
        DormData.Resident
FROM DormData;

它可以工作并合并我的记录,但问题是所有笔记都没有必要 列具有values.suppose,如果在一行中只有Note1和Note5中的值,那么它给出的输出如not1 ,,,, note5。但我希望它显示“Note1,Note5”

我该如何解决这个问题?

5 个答案:

答案 0 :(得分:1)

您可以在每个'Note1 *“,”'部分中使用Iif语句来检查空值。

Iif(IsNull(Note1), Note1, Note1 & ",")

我认为这应该有用。

答案 1 :(得分:1)

如果你想进入vba功能路线,以下功能将完成这项工作:

Function JoinStrings(Delimiter As String, _
                     ParamArray StringsToJoin() As Variant) As String
Dim v As Variant
    For Each v In StringsToJoin
        If Not IsNull(v) Then
            If Len(JoinStrings) = 0 Then
                JoinStrings = v
            Else
                JoinStrings = JoinStrings & Delimiter & v
            End If
        End If
    Next v
End Function

你会这样称呼:

JoinStrings(", ", Note1, Note2, Note3, Note4, Note5, Note6, Note7)

答案 2 :(得分:0)

关键是IIF() aka immediate if

例如,在Northwind sample database的订单表格中:     IIF(orders.ShipRegion IS NOT NULL,orders.ShipRegion&',',''

或更完整的查询:

SELECT 
    orders.OrderID, orders.CustomerID, orders.EmployeeID, 

    orders.ShipVia, orders.Freight, 
    (orders.ShipName & ',' & orders.ShipCity & ',' & IIF(orders.ShipRegion IS NOT NULL, orders.ShipRegion & ',', '') & orders.ShipPostalCode & ',' & orders.ShipCountry) AS Expr1
FROM orders
WHERE orders.[OrderID]=10282;

答案 3 :(得分:0)

您还可以使用Null表达式和连接在Access中的工作方式:

Note1 & (", " + Note2) & (", " + Note3)...

连接文本时,Access会将Null视为空字符串。但是如果你正在“添加”,Null会导致括号内的表达式导致Null。只要您的笔记不是数字,这将有效。

答案 4 :(得分:0)

对 TheOtherTimDuncan 解决方案的修改,可以很好地连接两个(或三个)注释。使用 IIF() 根据 Note1 是否为 Null 来设置分隔符或空白。它可能是这样的: Note1 & (IIF(Note1 Is Null, "",", ") + Note2) & (IIF((Note1 & Note2) Is Null, "",", ") + Note3)...