PostgreSQL子查询不起作用

时间:2013-12-19 07:49:44

标签: postgresql subquery

此查询有什么问题?

select extract(week from created_at) as week, 
       count(*) as received, 
       (select count(*) from bugs where extract(week from updated_at) = a.week) as done
from bugs as a
group by week

错误消息是:

  

列a.week不存在

更新:

根据第一条评论的建议,我试了一下:

select a.extract(week from created_at) as week, 
   count(*) as received, (select count(*) 
from bugs 
where extract(week from updated_at) = a.week) as done from bugs as a group by week  

但它似乎不起作用:

ERROR:  syntax error at or near "from"
LINE 1: select a.extract(week from a.created_at) as week, count(*) a...

2 个答案:

答案 0 :(得分:3)

据我所知,你根本不需要子选择:

select extract(week from created_at) as week, 
       count(*) as received, 
       sum( case when extract(week from updated_at) = extract(week from created_at) then 1 end) as done
from bugs 
group by week

这会计算每周的所有错误,并计算在“完成”的同一周内更新的错误。

请注意,如果表格中的表格不超过一年,您的查询将只报告正确的值。

如果表格中有一年以上的数据,您还需要在比较中包含年份:

select to_char(created_at, 'iyyy-iw') as week, 
       count(*) as received, 
       sum( case when to_char(created_at, 'iyyy-iw') = to_char(updated_at, 'iyyy-iw') then 1 end) as done
from bugs 
group by week

请注意,我使用IYYYIW来满足年度的ISO定义和年终/开始的周。


对原始查询无法解释的原因提出一些解释可能会有所帮助:

“外部”查询使用两个别名

  • 名为bugs
  • a的表别名
  • 名为extract(week from created_at)
  • 的表达式week的列别名

可以使用别名week位置在group by子句中。

对于子选择(select count(*) from bugs where extract(week from updated_at) = a.week)),别名a是可见的,但不是别名week(这就是SQL标准的定义方式)。

要使您的子选择工作(就列可见性而言),您需要引用“外部”列的完整表达式:

(select count(*) from bugs b where extract(week from b.updated_at) = extract(week from a.created_at)) 

请注意,我引入了另一个表别名b,以便明确哪个列来自哪个别名。

但即便如此,您也会遇到分组问题,因为您无法像这样引用未分组的列。

答案 1 :(得分:1)

可以正常工作

with origin as (
  select extract(week from created_at) as week, count(*) as received
  from bugs
  group by week
)
select week, received, 
  (select count(*) from bugs where week = extract(week from updated_at) )
from origin

它应该有一个好的表现