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

前端 未结 2 1604
青春惊慌失措
青春惊慌失措 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.

    0 讨论(0)
  • 2021-01-27 19:55

    I would consider creating a reference table with value field as it easier to maintain specially when the values change overtime.

    CREATE TABLE tblReference (field_txt text, val Integer);

    Get the field_txt with highest value and unique field then left join(inner join) to your current dataset.

    qry_field3_max = "SELECT [Field3],[commonField] FROM tblReference INNER JOIN (SELECT [commonField], MAX(val) as val FROM tblReference INNER JOIN tblNameTemp on tblReference.[field_txt]=tblNameTemp.[Field3] Group By [commonField]) as tbl_max_fields on tblReference.val=tbl_max_fields.val"

    0 讨论(0)
提交回复
热议问题