2013-01-31 89 views
0

我想算滿足此查詢條件的行數:如何計算分組記錄?

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)函數來計數記錄,但我需要在組內計數。

+1

查詢中沒有提到'eal_name'。其次,你爲什麼要做一個「獨特」的。 。 。連接產生太多的行? –

+0

是eal.eal_name唯一嗎? – Sebas

回答

0

我在eal.eal_name列中添加,因爲您沒有在查詢中使用它。所以你需要做的是在你想要的列上使用count()來獲得#s,再次添加該列,然後你需要添加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 
0

使用窗函數的try ...

這樣的...

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 

我ResultSet是

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