SQL按ID分组的行总和

时间:2013-03-12 22:31:16

标签: sql sql-server

这个SQL:

select Name,
       (select COUNT(1) from tbl_projects where statusId = tbl_sections.StatusId) as N
from tbl_sections
left join tbl_section_names on tbl_section_names.Id = NameId

生成以下数据:

Name    N
Completed   133
Cancelled   100
Unassigned  1
Sales   49
Development 10
Development 4
Development 1

我正在尝试修改它,以便按如下方式返回数据:

Name    N
Completed   133
Cancelled   100
Unassigned  1
Sales   49
Development 15

(即,总结名称相同的行)

有人能提出一些关于如何使这项工作的线索吗?我猜我需要一个SUM和一个GROUP BY,但它甚至都没有运行查询,因为我得到的只是错误。

5 个答案:

答案 0 :(得分:1)

尝试此查询。它汇总NName分组。

SELECT Name, SUM(N) 
FROM (
    SELECT Name,
    (SELECT COUNT(1) 
        FROM tbl_projects 
        WHERE statusId = tbl_sections.StatusId
    ) AS N
    FROM tbl_sections
    LEFT JOIN tbl_section_names ON tbl_section_names.Id = NameId
) a
GROUP BY a.Name

答案 1 :(得分:1)

试试这个

select Name, count(p.statusid) N
from tbl_sections
left join tbl_section_names on tbl_section_names.Id = NameId
left outer join tbl_projects p on tbl_sections.StatusId = p.statusId 
group by Name

答案 2 :(得分:0)

Select Name, Sum(N) from
    (select Name,
       (select COUNT(1) from tbl_projects where statusId = tbl_sections.StatusId) as N
    from tbl_sections
    left join tbl_section_names on tbl_section_names.Id = NameId)
group by Name

答案 3 :(得分:0)

此查询为您提供每个状态的计数,这意味着开发具有三个不同状态的部分,并且查询将反映这一点,如果您将状态添加为列,则更有意义:

select Name, tbl_sections.StatusId,
       (select COUNT(1) from tbl_projects where statusId = tbl_sections.StatusId) as N
from tbl_sections
left join tbl_section_names on tbl_section_names.Id = NameId

我不知道你的数据库的结构,但如果你想要计算每个名字的节数,可能是这样的。这基本上将查看连接的结果,然后通过告诉您每个唯一名称出现的次数来总结它:

select Name, count(*)
from tbl_sections
left join tbl_section_names on tbl_section_names.Id = NameId
Group By Name

答案 4 :(得分:0)

尝试一下。

select Name,
   SUM(select COUNT(1) from tbl_projects where statusId = tbl_sections.StatusId) as N
from tbl_sections
left join tbl_section_names on tbl_section_names.Id = NameId
group by Name