SQL Server where子句顺序计数> 0

时间:2017-04-01 16:41:30

标签: sql sql-server

我有一个有效但无法下订单的所有学生的查询。我只想要那些有订单的人。查询工作正常,直到我添加where子句。我该怎么写这个呢?

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

4 个答案:

答案 0 :(得分:2)

对于初学者,您可以用

替换where子句

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

答案 1 :(得分: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;

答案 2 :(得分:1)

你必须使用

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

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

答案 3 :(得分:1)

您不能在WHERE子句中使用列别名([Order count])。 <重复

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

在WHERE子句中

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

或使用cte。