admin

通过MAX挑战LEFT OUTER JOIN查询分组

sql

我有以下两个表:

BillingMatrixDefinition
    - id
    - amount

BillingMatrix
   - definition (FK to table above)
   - service_id (FK)
   - provider_id (FK)
   - amount (Decimal)

我需要获取所有具有service_idprovider_id指定的BillingMatrixDefinitions 。这是我目前拥有的SQL查询:

select def.id, service_id, provider_id, 
 (case when matrix.amount is not null then matrix.amount else def.amount end) amount
    from billing_billingdefinition def 
        left outer join billing_billingmatrix matrix
        on matrix.definition_id=def.id 
    where (service_id = 25 or service_id is null)
      and (provider_id = 24 or provider_id is null)

这给了我以下结果:

id      service_id  provider_id   amount
1       25          24            200.00
1       NULL        24            300.00
2       NULL        24            800.00
3       NULL        NULL          750.00
5       NULL        NULL          450.00
6       NULL        NULL          750.00

但是,我需要获取每个ID的结算金额,因此每个ID只能获得 一个
项目/金额id。在这种情况下,我想将项目获取到service_id=24,如果不存在,则将其获取到service_id=NULL

正确的查询应该给我以下结果:

id      service_id  provider_id   amount
1       25          24            200.00
2       NULL        24            800.00
3       NULL        NULL          750.00
5       NULL        NULL          450.00
6       NULL        NULL          750.00

请注意,现在没有1的重复条目,我使用已输入service_id的行项目(如果存在,则使用该条目,否则使用NULL)。什么是正确的查询来做到这一点?


阅读 171

收藏
2021-06-07

共1个答案

admin

另一种方式:

SELECT 
    def.id                                              AS id, 
    COALESCE(matrix.service_id, matrix2.service_id)     AS service_id, 
    COALESCE(matrix.provider_id, matrix2.provider_id)   AS provider_id, 
    COALESCE(matrix.amount, matrix2.amount, def.amount) AS amount 
FROM 
        billing_billingdefinition AS def 
    LEFT JOIN 
        billing_billingmatrix AS matrix 
            ON  matrix.definition_id = def.id 
            AND matrix.service_id = 25 
            AND matrix.provider_id = 24 
    LEFT JOIN 
        billing_billingmatrix AS matrix2
            ON  matrix2.definition_id = def.id 
            AND matrix2.service_id IS NULL
            AND matrix2.provider_id = 24  ;
2021-06-07