在联接PostgreSQL中的三个表后,如何计算记录总数?

时间:2018-12-28 06:54:46

标签: postgresql

我有一个查询,执行后给我总计12408条记录,但我希望这给我总计记录作为计数列

  

选择   c.complaint_id,c.server_time,c.completion_date,c.road_id,c.photo,c.dept_code,c.dist_code,c.eng_userid,c.feedback_type,c.status,p.dist_name,p.road_name,p。 road_dept,e.display_name,e.mobile   来自作为c INNER JOIN pwd_roads作为p ON的投诉p.road_id = c.road_id   INNER JOIN enc_details为e ON CAST(e.enc_code为INTEGER)= p.enccode   其中c.complaint_id = c.parent_complaint_id和c.dept_code ='PWDBnR'   和c.server_time在“ 2018-09-03”和“ 2018-12-19”之间

2 个答案:

答案 0 :(得分:0)

最简单但不太优雅的方法是:

select count(*)
from
( 
select c.complaint_id,c.server_time,c.completion_date,c.road_id,c.photo,c.dept_code,c.dist_code,c.eng_userid,c.feedback_type,c.status,p.dist_name,p.road_name,p.road_dept,e.display_name,e.mobile from complaints as c INNER JOIN pwd_roads as p ON p.road_id=c.road_id INNER JOIN enc_details as e ON CAST(e.enc_code as INTEGER) = p.enccode where c.complaint_id=c.parent_complaint_id and c.dept_code='PWDBnR' and c.server_time between '2018-09-03' and '2018-12-19'
)

答案 1 :(得分:0)

您可以使用窗口功能解决此问题。例如,如果您希望第一列是var ans2 = from w in workspend where DateTime.Parse("2018-12-28") <= w.Date && w.Date <= DateTime.Parse("2018-12-29") select new { w, (from cs in customers where cs.SearchTerms.LastIndexOf(w.Description.Substring(0, 2)) == cs.SearchTerms.Length - 2 select cs).FirstOrDefault().CustomerNo }; 语句完成的总行数:

SELECT

请注意,如果使用window函数,则在使用select count(1) over(range between unbounded preceding and unbounded following) as total_row_count , c.complaint_id,c.server_time,c.completion_date,c.road_id,c.photo,c.dept_code,c.dist_code,c.eng_userid,c.feedback_type,c.status,p.dist_name,p.road_name,p.road_dept,e.display_name,e.mobile from complaints as c INNER JOIN pwd_roads as p ON p.road_id=c.road_id INNER JOIN enc_details as e ON CAST(e.enc_code as INTEGER) = p.enccode where c.complaint_id=c.parent_complaint_id and c.dept_code='PWDBnR' and c.server_time between '2018-09-03' and '2018-12-19' 子句之前对其进行求值,因此,如果要向查询中添加LIMIT,则即使行数最大,行数也可能大于100将返回100行。