如何计算三个数据集

时间:2017-05-24 19:05:59

标签: sql sql-server sql-server-2008

我有3个数据集:公司,发布,发布,

我想算一下公司的数量'发布和发布。一些公司发布但没有编辑。 这是我的疑问:

SELECT company.name, company.id, count(*), 
       ( select count(*) 
         from post, postedited 
         where post.id=postedited.post_id) 
from company, post as p 
where company.id=p.company_id 
group by company_id 

帖子的结果是对的,但是postited的列是相同的。我的查询有什么问题?

2 个答案:

答案 0 :(得分:0)

您的子查询与主查询完全无关。它选择帖子和发布的和计数。您正在为主查询的每一行显示此结果。

您希望子查询与主查询的帖子相关。因此,从子句的子句中删除post表:

(select count(*) from postedited where postedited.post_id = p.id) 

现在,此子查询选择主查询记录的post_id的计数。最后你必须得到计数的总和:

select 
  c.name, c.id, count(*) as posts, 
  sum(select count(*) from postedited pe where pe.post_id = p.id) as edits
from company c
join post p on p.company_id = c.id
group by c.id;

你可以达到同样的目的:

select 
  c.name, c.id, count(distinct p.id) as posts, count(pe.post_id) as edits
from company c
join post p on p.company_id = c.id
left join postedited pe on pe.post_id = p.id
group by c.id;

答案 1 :(得分:0)

SELECT c.name AS companyName
    , c.id AS companyID
    , COUNT(DISTINCT p.id) AS postCount
    , COUNT(DISTINCT pe.post_id) AS postEditCount
FROM company c
LEFT OUTER JOIN post p ON p.Company_ID = c.ID
LEFT OUTER JOIN postEdited pe ON pe.Company_ID = c.ID
GROUP BY c.id, c.name

这将为您提供公司表中所有公司的列表,其中包含每个帖子和已编辑帖子的计数。如果您需要进一步查询该数据集,则可以。或者,您可以在上面的查询中添加WHERE子句以对其进行过滤。

我同意,请不要使用逗号语法。很容易产生意想不到的结果,并且它不能很好地表示您实际查询的内容。此外,它不再是标准的,并且在许多SQL版本中都被弃用。良好的JOIN语法将使您的生活更轻松。