2017-04-01 51 views
0

我有一個可以工作的查詢,但會返回所有學生,無論他們是否下訂單。我只想要那些有訂單的人。查詢工作正常,直到我添加where子句。我該如何正確寫這個?SQL Server where子句順序計數> 0

SELECT top 100 percent s.id, s.fname as [First Name], s.lname as [Last Name], 
(select count(student_id) from orderX x where x.student_id=s.id) as [Order Count], 
(select sum(no_attendees) from orderX x where x.student_id=s.id) as [Attendees/Participants], 
(select sum(eventHours) from orderX x where x.student_id=s.id) as [Event Hours], 
oc1.text as [Occupation 1], oc2.text as [Occupation 2], 
oc3.text as [Occupation 3], s.OccupationOther, s.dateGraduated, s.organization, s.city, s.zip, s.st, s.county, 
aud.text as [Preferred Audience], pts.text as [Plans to Share], mr.text as [Main Reason] 
FROM student s 
left join occupation1 oc1 on s.Occupation1 = oc1.id 
left join occupation2 oc2 on s.Occupation2 = oc2.id 
left join occupation3 oc3 on s.Occupation3 = oc3.id 
left join audience aud on s.audience = aud.id 
left join PlanToShare pts on s.PlanToShare = pts.id 
left join mainReason mr on s.mainReason = mr.id 

where [Order Count] > 0 
+0

什麼查詢...你確定沒有其他方式? –

+0

我知道這是醜陋的,但做的工作〜! – user2055729

+0

'Where語句不能識別你的列名。使用完整的查詢計數 – Fabio

回答

2

對於初學者來說,你可以通過

where (select count(student_id) from orderX x where x.student_id=s.id) > 0

+0

完美 - 謝謝:) – user2055729

+1

我寫「爲初學者」的原因是,雖然這解決了您的問題,但您的查詢應該以完全不同的方式構建。這就是爲什麼我贊同@GurV的回答,我建議你應該將其標記爲已接受。 –

1

取代你where條款你將不得不使用

where (select count(student_id) from orderX x where x.student_id=s.id) 

代替。在sql-server中,你不能在where子句中使用別名。

+0

是啊,看起來我輸入得太慢了! ;-)再次來得太遲:D – cars10m

+0

:-)雖然它不是一場競賽... –

1

您不能在WHERE子句中使用列別名([Order count])。無論是在WHERE子句中重複

(select count(student_id) from orderX x where x.student_id=s.id) 

WHERE (select count(student_id) from orderX x where x.student_id=s.id) > 0 

或使用CTE。

2

我認爲這裏不需要關聯。找到子查詢中的所有聚合和「內部」加入它(內在,因爲你反正要過濾出零計數行)

select top 100 percent s.id, 
    s.fname as [First Name], 
    s.lname as [Last Name], 
    x.order_count as [Order Count], 
    x.attendess_participants as [Attendees/Participants], 
    x.eventHours as [Event Hours], 
    oc1.text as [Occupation 1], 
    oc2.text as [Occupation 2], 
    oc3.text as [Occupation 3], 
    s.OccupationOther, 
    s.dateGraduated, 
    s.organization, 
    s.city, 
    s.zip, 
    s.st, 
    s.county, 
    aud.text as [Preferred Audience], 
    pts.text as [Plans to Share], 
    mr.text as [Main Reason] 
from student s 
left join occupation1 oc1 on s.Occupation1 = oc1.id 
left join occupation1 oc2 on s.Occupation2 = oc2.id 
left join occupation1 oc3 on s.Occupation3 = oc3.id 
left join audience aud on s.audience = aud.id 
left join PlanToShare pts on s.PlanToShare = pts.id 
left join mainReason mr on s.mainReason = mr.id 
inner join (
    select student_id, 
     count(*) as order_count, 
     sum(no_attendees) as attendess_participants, 
     sum(eventHours) as event_hours 
    from orderX x 
    group by student_id 
    ) x on x.student_id = s.id; 
+1

效率很高,運行時間很短 - 非常感謝分享! – user2055729