简体   繁体   中英

SQL query for getting count on same table using left outer join

I have a table from which I need to get the count grouped on two columns.

The table has two columns one datetime column and another one is success value(-1,1,0) What i am looking for is something like this:

Count of success value for each month:

month----success-----count
11------- -1 ------- 50

11------- 1 --------- 50

11------- 0 ------- 50

12------- -1 ------- 50

12------- 1 ------- 50

12------- 0 ------- 50

If there is no success value for a month then the count should be null or zero. I have tried with left outer join as well but of no use it gives the count incorrectly.

You need to cross join all the available months, against the 3 success values to build a virtual matrix, which can then be left joined to the actual data

select m.month, s.success, COUNT(t.month)
from (select distinct MONTH from tbl) m
cross join (select -1 success union all select 1 union all select 0) s
left join tbl t on t.month = m.month and t.success = s.success
group by m.month, s.success

If you need missing months as well, that can be done, just slightly more complicated by changing the subquery "m" above.

@updated Count(*) will always return at least 1 for left joins. count(colname) from the right part of the left join to be correct.

您可能需要一个仅包含1-12值的表进行连接,以便获得零计数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM