How to SQL join tables, selecting the largest value in Access-VBA Function?

前端 未结 2 1605
青春惊慌失措
青春惊慌失措 2021-01-27 19:16

I currently have the following Access VBA function, which operates as explained in a previous question (very useful for understanding this question):

Private Fun         


        
2条回答
  •  礼貌的吻别
    2021-01-27 19:48

    Encode value, decode max this way in SQL.

    Currently you are building SQL command as (i replaced table name variables with arbitrary values, temp and tableName )

    SELECT tbl_grp_by.*, [tableName].*  
    INTO newTableName 
    FROM (
        SELECT Max([temp].[Field1]) as [Field1], 
            Max([temp].[Field2]) as [Field2],  
            Max([temp].[Field3]) as [maxField3], 
            [temp].[Field4] as [Field4]  
        FROM [temp]
        INNER JOIN [tableName ]
           ON [temp].[commonField] = [tableName].[commonField] 
        GROUP BY [temp].[commonField]
     ) as tbl_grp_by  
    INNER JOIN [tableName]
      ON [tableName].[commonField] = tbl_grp_by.[commonField]
    

    Build it as

    SELECT tbl_grp_by.[Field1],tbl_grp_by.[Field2],
        Switch( 
            tbl_grp_by.[maxfield3] = 0, '0',
            tbl_grp_by.[maxfield3] = 1, '>1 million',
            tbl_grp_by.[maxfield3] = 2 '0001-0010' 
        ) as [Field3],   
        tbl_grp_by.[Field4],
    [tableName].*  
    INTO newTableName 
    FROM (
        SELECT Max([temp].[Field1]) as [Field1], 
            Max([temp].[Field2]) as [Field2],  
            Max(Switch(  
                [temp].[field3] = '0' , 0,
                [temp].[field3] = '>1 million' , 1,
                [temp].[field3] = '0001-0010', 2  
             ))as [maxField3], 
            [temp].[Field4] as [Field4]  
        FROM [temp]
        INNER JOIN [tableName ]
           ON [temp].[commonField] = [tableName].[commonField] 
        GROUP BY [temp].[commonField]
     ) as tbl_grp_by  
    INNER JOIN [tableName]
      ON [tableName].[commonField] = tbl_grp_by.[commonField]   
    

    So [field3] is encoded under max() in the inner query and that max is decoded in outer query.

提交回复
热议问题