2

这个 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,但它甚至从不运行查询,因为我得到的只是错误。

4

5 回答 5

1

试试这个查询。它N按 分组Name

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
于 2013-03-12T22:34:16.127 回答
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
于 2013-03-12T22:36:12.910 回答
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
于 2013-03-12T22:33:57.197 回答
0

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

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
于 2013-03-12T22:37:12.123 回答
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
于 2013-03-12T22:37:33.657 回答