2012-07-18 92 views
2

考慮下面的查詢,這將給學生姓史密斯的數的計數對於給定的報名(主題)TSQL計數

SELECT 
    e.EnrolmentId, 
    COUNT((CASE WHEN s.Surname LIKE 'Smith' THEN 1 ELSE NULL END)) AS CountIf 
FROM 
    Enrolment e 
INNER JOIN StudentEnrolment se 
    ON e.EnrolmentId = se.EnrolmentId 
INNER JOIN Student s 
    ON se.StudentId = s.StudentId 
GROUP BY 
    e.EnrolmentId 

是否有可能有「史密斯」作爲參數,如果更改爲COUNT和SUM爲0,而不是空else部分,它應該工作是這樣的

COUNT((CASE WHEN s.Surname LIKE @Surname THEN 1 ELSE NULL END)) AS CountIf 

回答

3

,不是嗎?

SELECT 
    e.EnrolmentId, 
    SUM((CASE WHEN s.Surname LIKE 'Smith' THEN 1 ELSE 0 END)) AS CountIf 
FROM 
    Enrolment e 
INNER JOIN StudentEnrolment se 
    ON e.EnrolmentId = se.EnrolmentId 
INNER JOIN Student s 
    ON se.StudentId = s.StudentId 
GROUP BY 
    e.EnrolmentId 

實施例:

declare @t as varchar(20) 
select @t='ricardo' 

declare @ta as table 
(
    name varchar(30) 
) 

insert into @ta 
values 
('juan'), 
('ricardo'), 
('pablo') 


select 
SUM((CASE WHEN name LIKE @t THEN 1 ELSE 0 END)) AS CountIf 
from @ta 

輸出:

CountIf 
----------- 
1 
+0

貌似選擇子句將工作在參數。只需要測試什麼時候從.NET代碼中調用。 – Craig 2012-07-18 03:51:38

+0

@Craig它也能工作。應該沒有任何區別。 – Icarus 2012-07-18 03:53:49

+0

謝謝,我真的不認爲參數選擇將工作。 – Craig 2012-07-18 03:54:47