使用左外连接获取同一个表的计数的 SQL 查询
我有一个表,我需要从中获取按两列分组的计数。
该表有两列,一列是 datetime
列,另一列是成功值(-1,1,0) 我正在寻找的是这样的:
每个月的成功值计数:
月----成功-----计数
11-------- -1 ------- 50
11-------- 1 --------- 50
11------ - 0 ---------- 50
12-------- -1 -------- 50
12-------- 1 ---------- 50
12----- 0 ------- 50
如果一个月没有成功值,则计数应为 null
或零。 我也尝试过使用左外连接,但没有用,它给出的计数不正确。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要交叉连接所有可用月份,针对 3 个成功值来构建一个虚拟矩阵,然后可以将其与实际数据连接起来。
如果您还需要丢失月份,也可以这样做,只是通过更改稍微复杂一些上面的子查询“m”。
@更新
对于左连接,Count(*) 始终至少返回 1。从左连接的右侧部分开始计数(colname)是正确的。
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
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 之间的值的表来连接,以便获得零计数。
You probably need a table with the just the values from 1-12 to join with so you can get a zero count.