sql - How to use Union or Intersect instead of an OR in my Join -
the query below works, i've read, or
in join
not efficient way results. think maybe should using union
or intersect
, can't figure out how accomplish that. can explain 'proper' results?
with cte1 (select sc, sn, count(al) unexcused att al = 'u' group sc, sn), cte2 (select sc, sn, count(al) suspended att al = 's' group sc, sn) select stu.id, stu.sc, stu.sn, isnull(cte1.unexcused, '') unx, isnull(cte2.suspended, '') sus cte2 full join cte1 on cte1.sc = cte2.sc , cte1.sn = cte2.sn join stu on (cte1.sc = stu.sc , cte1.sn = stu.sn) or (cte2.sc = stu.sc , cte2.sn = stu.sn) stu.sc in (1,2,4,9,11,15)
this sample of output:
id sc sn unx sus 4291432 15 602 0 8 4296250 15 688 6 3 4216462 15 695 0 12 4916602 15 623 0 2 4295193 1 150 1 0 4215874 2 216 1 0 4005707 15 297 1 0
thank you.
personally, i'd change query around this:
with cte1 (select sc, sn, count(al) unexcused att al = 'u' group sc, sn), cte2 (select sc, sn, count(al) suspended att al = 's' group sc, sn) select stu.id, stu.sc, stu.sn, isnull(cte1.unexcused, '') unx, isnull(cte2.suspended, '') sus stu left join cte1 on (cte1.sc = stu.sc , cte1.sn = stu.sn) left join cte2 on (cte2.sc = stu.sc , cte2.sn = stu.sn) stu.sc in (1,2,4,9,11,15)
.... if no other reason makes intended results little more clear. note optimizer may still generate same explain plan.
Comments
Post a Comment