2013-08-26 54 views
0

我的表有醫生ID,訪問ID(一個醫生能有幾個訪問),並參觀原因,它看起來像這樣:如何根據t-sql中的條件對一列的值進行分組?

doctor_uid | visit_uid | visit_cause 
11-11-11 22-22-11  1 
22-22-22 44-44-22  2 
11-11-11 23-23-23  1 

我需要統計每個醫生的所有訪問,基於visit_cause(應該等於'1')。以前我算每個醫生的所有訪問無visit_cause條件,我必須在我的查詢有這樣太:

SELECT 
    v.vra_uid, 
    COUNT(v.visit_uid) OVER (PARTITION BY v.vra_uid) AS number_of_visits 
FROM visits v 

它返回:

doctor_uid | number_of_visits 
    11-11-11 2  
    22-22-22 1  

我怎麼能指望這些訪問,有visit_cause = '1'爲每個醫生?所以它看起來像:

doctor_uid | number_of_visits | visits_with_cause_equal_1 
    11-22-33 2       2 
    22-22-22 1       0 

在此先感謝!

回答

1

這應該工作:

select v.vra_uid, COUNT(v.visit_uid) as number_of_visits , SUM(case when v.visit_cause = 1 then 1 else 0 end) as visits_with_cause_equal_1 
from visits v 
group by v.vra_uid 
0

你試過CASE WHEN visit_cause = '1' THEN COUNT(*)

相關問題