下面的SQL代码概述了我的客户以及他们在2015年12月所做的订单。我想用UNION做这件事。
select k.klantnr, k.naam, count(b.bestelnr) as 'aantal bestellingen'
from klant k LEFT JOIN bestelling b on k.klantnr = b.klantnr and Year (b.besteldatum) = 2015 and Month(b.besteldatum) = 12
group by k.klantnr, k.naam
我已经尝试过了:
select klantnr from klant
union
select klantnr, count(*) from bestelling
where Year(besteldatum) = 2015 and Month(besteldatum) = 12
group by klantnr
显然没有给我这个错误:使用UNION,INTERSECT或EXCEPT运算符组合的所有查询在目标列表中必须具有相同数量的表达式。
当我在谷歌搜索时,我发现了下一个查询:
select tem.klantnr, count(*)
from(select klantnr from klant
union
select klantnr from bestelling where Year(besteldatum) = 2015 and Month(besteldatum) = 12) as tem
group by klantnr
没有给我每个客户的订单数。
答案 0 :(得分:0)
您可以使用OUTER APPLY执行此操作:
select k.klantnr, k.naam, orders.cnt as 'aantal bestellingen'
from klant k
outer apply (
select count(*)
from bestelling
where klantnr = k.klantnr
and Year(besteldatum) = 2015
and Month(besteldatum) = 12
) as orders(cnt);
答案 1 :(得分:0)
您想要所有客户以及指定月份的订单数量吗?
您可以使用外部申请作为Ruslan建议或离开加入。
select k.klantnr,coalesce(count(b.klantnr),0) as 'aantal bestellingen'
from klant k
left join bestelling b on k.klantnr = b.klantnr and Year(besteldatum) = 2015 and Month(besteldatum) = 12)
group by klantnr
答案 2 :(得分:0)
如果你真的需要UNION,并且你可以处理输出,这里有一些SQLi风格的查询:D
select klantnr, null from klant union
select klantnr, count(*) from bestelling
where Year(besteldatum) = 2015
and Month(besteldatum) = 12 group by klantnr