如何从不同的月份和状态获得COUNT的0?

时间:2014-07-16 17:40:09

标签: sql sqlite count left-join web2py

我有两张表itemstatus

item是这样的表格:

id   date          status_id
1    10-02-2013    1
2    11-02-2013    1        
3    11-03-2013    2        
...  ...           ...

status是这样的表格:

id      status_name 
1       first       
2       second   
3       three
...     ...

我希望结果是这样的:

month   status   total
2       first    2
2       second   0
2       three    0
3       first    0
3       second   1
3       three    0

我通过web2py使用SQLite:

select 
      month, status.status_name, ifnull(total, 0)
from 
     status
left join                           
     (select 
            status.id,
            strftime('%m', date) as month, 
            status_name as status,
            count(status_name) as total                     
      from 
          status 
      inner join 
          item
      on status.id = item.status_id
      group by nombre, web2py_extract('month', date)
      ) sub                  
on sub.id = status.id

我使用函数web2py_extract按月分组date

我的结果是下一个:

month   status   total
2       first    2
3       second   1

但是,我没有得到空值的行。我做错了什么?

3 个答案:

答案 0 :(得分:1)

您可以使用cross join然后left outer join

执行此操作
select m.month, s.status, coalesce(i.cnt, 0) as cnt
from (select distinct strftime('%m', date) as month from item) m cross join
     (select id, status from status) s left outer join
     (select strftime('%m', date) as month, status_id, count(*) as cnt
      from item i
      group by strftime('%m', date), status_id
     ) i
     on i.month = m.month and i.status_id = s.id;

cross join创建月份和状态的所有组合。 left join带来了计数。当没有匹配时,coalesce()会将NULL转换为0

答案 1 :(得分:0)

无论如何,您想要的具有不匹配值的表必须位于LEFT JOIN的左侧。 这意味着您需要在内部查询中使用item LEFT JOIN status。 (外部查询不需要外部联接。)

答案 2 :(得分:0)

SELECT MONTH(date) as Month, Status.status_name, COUNT(*) as Total 
FROM  Item 
LEFT JOIN Status on Item.status_id = Status.id