小编mul*_*lus的帖子

使用LEFT JOIN查询不返回计数为0的行

我试图让以下内容为PostgreSQL中使用左连接的每个组织返回一个计数,但我无法弄清楚为什么它不起作用:

  select o.name as organisation_name,
         coalesce(COUNT(exam_items.id)) as total_used
  from organisations o
  left join exam_items e on o.id = e.organisation_id
  where e.item_template_id = #{sanitize(item_template_id)}
  and e.used = true
  group by o.name
  order by o.name
Run Code Online (Sandbox Code Playgroud)

使用coalesce似乎不起作用.我的智慧结束了!任何帮助肯定会受到赞赏!

为了澄清什么不起作用,目前查询只返回计数大于0的组织的值.我希望它为每个组织返回一行,而不管计数如何.

表定义:

TABLE exam_items
  id serial NOT NULL
  exam_id integer
  item_version_id integer
  used boolean DEFAULT false
  question_identifier character varying(255)
  organisation_id integer
  created_at timestamp without time zone NOT NULL
  updated_at timestamp without time zone NOT NULL
  item_template_id integer
  stem_id integer
  CONSTRAINT exam_items_pkey PRIMARY …
Run Code Online (Sandbox Code Playgroud)

sql postgresql count left-join

31
推荐指数
2
解决办法
3万
查看次数

标签 统计

count ×1

left-join ×1

postgresql ×1

sql ×1