简体   繁体   English

使用左外部联接在同一表上获取计数的SQL查询

[英]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: 该表有两列,一列为datetime列,另一列为成功值(-1,1,0),我正在寻找的是这样的:

Count of success value for each month: 每个月的成功价值计数:

month----success-----count 月----成功--------计数
11------- -1 ------- 50 11 ------- -1 ------- 50

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

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

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

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

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

If there is no success value for a month then the count should be null or zero. 如果一个月没有成功值,则计数应为null或零。 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 您需要将所有可用月份与3个成功值交叉连接,以建立虚拟矩阵,然后可以将其与实际数据保持连接

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. 如果您还需要缺少月份,则可以通过更改上面的子查询“ m”来完成,只是稍微复杂一点。

@updated Count(*) will always return at least 1 for left joins. @updated Count(*)对于左连接总是返回至少1。 count(colname) from the right part of the left join to be correct. 左边连接的右边的count(colname)是正确的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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