我想计算符合此查询条件的行数:
Select DISTINCT(projects.project_id)
, projects.project_name
, CONVERT(char(11), projects.kickoff_date, 102) AS kickoff_date
, status_phase.status_name
, eal.eal_abbrv
, tech_types.tech_name
from projects
INNER JOIN tech_assigned
ON projects.project_id = tech_assigned.project_id
INNER JOIN tech_types
ON tech_assigned.tech_id = tech_types.tech_id
inner join status_phase
on projects.status_phase_id=status_phase.status_phase_id
inner join eal
on projects.eal_id=eal.eal_id
where status_phase.status_id <= 2
order by eal.eal_abbrv
我希望计数按eal.eal_name列分组,但是当我尝试这样做时,我会在选择列表中看到可怕的“列'projects.project_id'
无效,因为它不包含在聚合函数或者GROUP BY子句。“错误信息。我可以使用Select COUNT(*)
或COUNT(1)
函数对记录进行计数,但我需要在组内进行计数。
答案 0 :(得分:0)
我正在添加eal.eal_name列,因为您的查询中没有它。所以你需要做的是在你希望得到#s的列上的count(),再次添加该列,然后你需要添加GROUP BY子句并添加你选择的每一列。
Select DISTINCT(projects.project_id)
, projects.project_name
, count(eal.eal_name)
, eal.eal_name
, CONVERT(char(11), projects.kickoff_date, 102) AS kickoff_date
, status_phase.status_name
, eal.eal_abbrv
, tech_types.tech_name
from projects
INNER JOIN tech_assigned
ON projects.project_id = tech_assigned.project_id
INNER JOIN tech_types
ON tech_assigned.tech_id = tech_types.tech_id
inner join status_phase
on projects.status_phase_id=status_phase.status_phase_id
inner join eal
on projects.eal_id=eal.eal_id
where status_phase.status_id <= 2
group by projects.project_id
, projects.project_name
, eal.eal_name
, CONVERT(char(11), projects.kickoff_date, 102)
, status_phase.status_name
, eal.eal_abbrv
, tech_types.tech_name
order by eal.eal_abbrv
答案 1 :(得分:0)
尝试使用窗口函数...
像这样...... declare @table table (a int, b int)
insert into @table
values (0,0),(0,1),(0,1),(1,2)
select *
,COUNT(*) over () as [count all]
,COUNT(*) over (partition by a) as [count as grouped by a]
,COUNT(*) over (partition by a,b) as [count as grouped by a and b]
from @table T
我的结果集是
a b count all count as grouped by a count as grouped by a and b
0 0 4 3 1
0 1 4 3 2
0 1 4 3 2
1 2 4 1 1
您的查询中的应为
Select DISTINCT(projects.project_id)
, count(*) over (partition by eal.eal_name) as [count by eal_name]
, projects.project_name
, CONVERT(char(11), projects.kickoff_date, 102) AS kickoff_date
, status_phase.status_name
, eal.eal_abbrv
, tech_types.tech_name
from projects
INNER JOIN tech_assigned
ON projects.project_id = tech_assigned.project_id
INNER JOIN tech_types
ON tech_assigned.tech_id = tech_types.tech_id
inner join status_phase
on projects.status_phase_id=status_phase.status_phase_id
inner join eal
on projects.eal_id=eal.eal_id
where status_phase.status_id <= 2
order by eal.eal_abbrv