我有这个查询:
SELECT R.IDrota, (SELECT count(*) FROM VendaVoo where ocupacao = 1 and IDvoo= V.IDvoo and V.IDrota = R.IDrota) as VENDAS FROM voo V
JOIN VendaVoo VV ON VV.IDvoo = V.IDvoo
JOIN rota R ON V.IDrota = R.IDrota
GROUP BY R.IDrota, V.IDvoo, V.IDrota
order by IDrota
这给了我这张桌子:
此表重复了一些“ IDrota”。我的目标是求和,以至于拥有唯一的“ IDrota”值。
答案 0 :(得分:4)
您可以使用sum()
和case
来获得所需的结果。不需要subquery
。 grouping
只能由IDrota
SELECT R.IDrota,
sum(case when VV.ocupacao = 1 then 1 else 0 end) as VENDAS
FROM voo V
JOIN VendaVoo VV ON VV.IDvoo = V.IDvoo
JOIN rota R ON V.IDrota = R.IDrota
GROUP BY R.IDrota
order by R.IDrota
答案 1 :(得分:1)
我认为您只需要条件聚合:
SELECT R.IDrota,
SUM(CASE WHEN vv.ocupacao = 1 THEN 1 ELSE 0 END) as Vendas
FROM voo V JOIN
VendaVoo VV
ON VV.IDvoo = V.IDvoo JOIN
rota R
ON V.IDrota = R.IDrota
GROUP BY R.IDrota
ORDER BY R.IDrota;