【问题标题】:SQL query that loops through multiple values from same column for one row循环遍历同一列中的多个值的 SQL 查询一行
【发布时间】:2014-06-10 14:46:24
【问题描述】:

我有 2 个给定的表 (table_A, Table_B) 和

需要有关子查询的帮助或从列TABLE_A.DESCRIPString 中选择多个值的可能解决方案

TABLE_A:
ID     PARTNUM     DESCRIPString
1      4456        121~134~111
2      4457        122~111
3      4458        122~134
4      4459        111
5      4460        121~134~111

TABLE_B.DESCRIPID交叉匹配

TABLE_B:
ID     DESCRIPID   DECSRIPLong
1      121         Silver
2      122         Black
3      111         Mask
4      134         Pickle

最后显示以下内容:

Table_AB

ID     PARTNUM     DESCRIPString    PARTDESCRIP
1      4456        121~134~111      Silver~Pickle~Mask
2      4457        122~111          Black~Mask
3      4458        122~134          Black~Pickle
4      4459        111              Mask
5      4460        121~134~111      Silver~Pickle~Mask

我知道大多数人会建议将数据库重做为每列单个变量,但是在这种情况下无法这样做。

【问题讨论】:

    标签: sql ms-access subquery string-matching multiple-variable-return


    【解决方案1】:

    将此函数放入模块并运行此查询。它应该给你要求的结果。您没有指定数据类型,所以我在函数中使用了变体。

    Public Function fnParseDescr(strWork As Variant) As String
    Dim vEnd
    Dim strTemp As String
    Dim strLook As String
    Dim strResult As String
    strResult = ""
    strWork = Trim(CStr(strWork))
    Do While Len(strWork) > 0
        If InStr(strWork, "~") = 0 Then
            strLook = Trim(DLookup("[DESCRIPLong]", "TABLE_B", "[DESCRIPID] = CVar('" & strWork & "')"))
            strResult = strResult & "~" & strLook
            strWork = ""
        Else
            vEnd = InStr(strWork, "~") - 1
            strTemp = Left(strWork, vEnd)
            strLook = Trim(DLookup("[DESCRIPLong]", "TABLE_B", "[DESCRIPID] = CVar('" & strTemp & "')"))
            strResult = strResult & "~" & strLook
            strWork = Right(strWork, (Len(strWork) - (vEnd + 1)))
            strTemp = ""
            strLook = ""
        End If
    Loop
    If Left(strResult, 1) = "~" Then strResult = Right(strResult, (Len(strResult) - 1))
    fnParseDescr = strResult
    Exit Function
    End Function
    
    
    SELECT ID,
        PARTNUM, 
        DESCRIPString, 
        fnParseDescr([DESCRIPString]) AS PARTDESCRIP
    FROM TABLE_A;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 2021-11-17
      • 2015-12-11
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多