SQL Joining by field that *may* be empty

后端 未结 2 1041
滥情空心
滥情空心 2021-01-23 04:59

In my SQL CE database I have three tables: customer, list and customerlist (a junction table between customer and list<

相关标签:
2条回答
  • 2021-01-23 05:29

    You must use LEFT JOIN syntax.

    select list.listid,  case when count(customerlist.customerid) is null then 0 else count(customerlist.customerid) end as numppl, list.ShortDesc
    from list left join customerlist on list.listid=customerlist.listid
    group by list.ShortDesc, list.listid
    order by numppl desc
    

    Or you can use RIGHT JOIN :

    select list.listid, case when count(customerlist.customerid) is null then 0 else count(customerlist.customerid) end as numppl, list.ShortDesc
    from customerlist right join list on customerlist.listid=list.listid
    group by list.ShortDesc, list.listid
    order by numppl desc
    

    Use COALESCE :

    select list.listid,  coalesce(count(customerlist.customerid),0) as numppl, list.ShortDesc
    from list left join customerlist on list.listid=customerlist.listid
    group by list.ShortDesc, list.listid
    order by numppl desc
    
    0 讨论(0)
  • 2021-01-23 05:39

    Use LEFT JOIN instead with ISNULL to replace NULL with 0:

    SELECT 
      list.listid, 
      ISNULL(count(customerlist.customerid), 0) AS numppl, 
      list.ShortDesc
    FROM list 
    LEFT JOIN customerlist ON list.listid = customerlist.listid
    GROUP BY list.ShortDesc, 
             list.listid
    ORDER BY numppl DESC;
    

    SQL Fiddle Demo


    Update

    For SQL Server CE, try this:

    SELECT 
      list.listid, 
      SUM(CASE WHEN customerlist.customerid IS NULL THEN 0 ELSE 1 END) AS numppl, 
      list.ShortDesc
    FROM list 
    LEFT JOIN customerlist ON list.listid = customerlist.listid
    GROUP BY list.ShortDesc, 
             list.listid
    ORDER BY numppl DESC;
    
    0 讨论(0)
提交回复
热议问题