How to set a default row for a query that returns no rows?

后端 未结 11 1451
青春惊慌失措
青春惊慌失措 2020-12-03 06:43

I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I\'m only returning a single column from this particular table

11条回答
  •  温柔的废话
    2020-12-03 07:03

    How about this:

    SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate
    FROM 
      (SELECT 0) DEF (Rate) -- This is your default rate
    LEFT JOIN (
      select rate 
      from d_payment_index
      --WHERE 1=2   -- Uncomment this line to simulate a missing value
    
      --...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes...
      --where fy = 2007
      -- and payment_year = 2008
      --  and program_id = 18
    ) ACTUAL (Rate) ON 1=1
    

    Results

    Valid Rate Exists

    Rate        Rate        UseThisRate
    ----------- ----------- -----------
    0           1           1
    

    Default Rate Used

    Rate        Rate        UseThisRate
    ----------- ----------- -----------
    0           NULL        0
    

    Test DDL

    CREATE TABLE d_payment_index (rate int NOT NULL)
    INSERT INTO d_payment_index VALUES (1)
    

提交回复
热议问题