2012-09-26 73 views
1

當我運行此查詢:SQL案例

select 
    '1992' = CASE WHEN Year(HireDate) = 1992 THEN count(*) END, 
    '1993' = CASE WHEN Year(HireDate) = 1993 THEN count(*) END, 
    '1994' = CASE WHEN Year(HireDate) = 1994 THEN count(*) END 
    from employees 
group by Year(HireDate) 

我得到:

1992  1993  1994 
3  NULL  NULL 
NULL  3  NULL 
NULL  NULL  3 

我如何更改查詢來獲取:

1992 1993 1994 
3   3  3 
+0

'max(case wehn ...' –

回答

3

與此查詢你只會得到一行:

select 
'1992'= 
count(CASE WHEN Year(HireDate) = 1992 THEN 1 END), 
'1993' = 
count(CASE WHEN Year(HireDate) = 1993 THEN 1 END), 
'1994' = 
count(CASE WHEN Year(HireDate) = 1994 THEN 1 END) 
from employees 
+0

謝謝你這麼多! – user1508682

+0

@ user1508682:如果這個答案實際上對你有幫助,請考慮[正式接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work「如何接受答案的工作?「)下次你在這裏。 –

1
select 
    '1992' = sum (case when year(HireDate) = 1992 THEN 1 else 0 END), 
    '1993' = sum (case when year(HireDate) = 1993 THEN 1 else 0 END), 
    '1994' = sum (case when year(HireDate) = 1994 THEN 1 else 0 END), 
from employees