2013-06-19 63 views
2

我有以下的列的SQL表需要得到幫助的得到的計數與分組


表1

Site Det FailFlag Comments ModifiedDate ModifiedBy  
ABT A01  F  Dfasdf 10/11/2011 Anna 
ABT A01  F  dsfsdf 15/12/2012 Mand 
ABT A01   Rds  30/03/2011 Tim 
ABT A01   GHDs  02/12/2012 Andy 
ABT A02  F  dfd  09/05/2012 Anna 
ABT A02   sdada  11/02/2013 Kathy 
ABT A02   Dfg  15/05/2011 Rob 
TRG A01   sdasd  16/04/2010 Richard 
TRG K05   jksdh  23/04/2012 Mark 
KLD KO5  F  sd  18/05/2013 Jim 
KLD KO5   dsfsd  10/03/2012 James 
KLD KO5   sdsd  12/05/2011 Luther 

我需要得到以下的輸出:

Site Det Count CountOfFailures 
ABT A01  4  2 
ABT A02  3  1 
TRG A01  1  0 
TRG K05  1  0 
KLD KO5  3  1 

我知道我可以按Site和Det分組並獲得計數但無法獲得故障次數

Select Site,Det, Count(*) AS [Count] from Table1 
group by Site,Det order by Count 

需要幫助。

+0

需要by子句,情況FailFlag = 'F' THEN 1 ELSE 0 AS FailFlagNum和不到哪裏或組指望它增加的情況下。 – mirkobrankovic

回答

2

試試這個: -

Select site,det, 
    FlagCount = sum(case when FailFlag='F' then 1 else 0 ENd) 
    from yourTable 
    group by Site,Det 
    order by Site 

輸出

+------+-----+-----------+ 
    | site | det | FlagCount | 
    +------+-----+-----------+ 
    | ABT | A01 |   2 | 
    | ABT | A02 |   1 | 
    | KLD | KO5 |   1 | 
    | TRG | A01 |   0 | 
    | TRG | K05 |   0 | 
    +------+-----+-----------+ 
+0

謝謝Praveen。這正是我一直在尋找的。這很好。 – user1483122

2

你可以嘗試一個case語句。

SELECT Site, Det, COUNT(*) AS [Count], SUM(CASE WHEN FailFlag = 'F' THEN 1 ELSE 0 END) AS CountOfFailures 
FROM Table1 
GROUP BY Site, Det 
1

如何像

Select [Site], 
     [Det], 
     Count(*) AS [Count], 
     SUM(CASE WHEN FailFlag = 'F' THEn 1 ELSE 0 END) [CountFailed] 
from Table1 
group by [Site], 
      [Det] 
order by [Count]