SQL:在表中包含计数中的零

时间:2018-04-17 20:03:01

标签: sql mariadb

我有一张这样的表:

+---------+---------+
|   id1   |   id2   |
+---------+---------+
|       1 |       2 |
|       2 |       2 |
|       3 |       1 |
|       4 |       1 |
|       5 |       3 |
|       6 |       2 |
+---------+---------+

我想,对于每个id2,计算与之关联的id1的数量,包括零值。目前我有这个:

select id2, count(*) cnt 
from mytable group by id2

部分工作,除了它产生这个输出:

+---------+---------+
|   id2   |   cnt   |
+---------+---------+
|       1 |       2 |
|       2 |       3 |
|       3 |       1 |
+---------+---------+

我想获得这样的输出:

+---------+---------+
|   id2   |   cnt   |
+---------+---------+
|       1 |       2 |
|       2 |       3 |
|       3 |       1 |
|       4 |       0 |
|       5 |       0 |
|       6 |       0 |
+---------+---------+

我怎么能实现这个目标? 谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用LEFT JOIN

来使用以下内容
SELECT id1, IFNULL(cnt, 0) AS IDs FROM table1 LEFT JOIN (
    SELECT id2, count(*) cnt FROM table1 GROUP BY id2
)x ON table1.id1 = x.id2
  

演示: http://sqlfiddle.com/#!9/e97c4e/2/0

答案 1 :(得分:0)

您需要一个包含结果集中所需值的表格。然后有几种方法。 。 。例如,相关子查询:

var options = { path: '/api/data/v8.2/contacts?$select=address1_city,address1_line1,address1_line2,address1_line3,contactid,emailaddress1,firstname,fullname,middlename,mobilephone,statecode,suffix,telephone1,vcm_npiid,vcm_prescriberspeciality,vcm_prescriberstatus,vcm_recordtype,vcm_symphonyid&$orderby=fullname asc&$filter=statecode eq 0',
  host: 'xxxxxx.crm.dynamics.com',
  method: 'GET',
  headers:
   { Authorization: 'Bearer xxxxxxx',
     Accept: 'application/json',
     'Content-Type': 'application/json; charset=utf-8',
     Prefer: 'odata.includeannotations=OData.Community.Display.V1.FormattedValue',
     'OData-MaxVersion': '4.0',
     'OData-Version': '4.0' 
   } 
} 

var crmrequest = https.request(options, function(response) { ... }

答案 2 :(得分:0)

你应该试图弄清楚有多少Id2与Id1匹配,你可以通过表的左连接来实现这一点。

SELECT 
  mt1.Id1, 
  COUNT(mt2.Id2) 
FROM 
  MyTable as mt1 LEFT JOIN MyTable as mt2 ON mt1.Id1 = mt2.Id2
GROUP BY
  mt1.Id1

将包含id1的所有值,并计算id2的所有匹配项。如果Id1不匹配,则计数为0。