在Sub查询select语句SQL中计算Aggregate值

时间:2017-03-15 05:58:16

标签: sql

我想运行此查询,但它给了我错误。

专栏' Order.OrderId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

这是我的问题:

SELECT vc.VehicleCategoryName,
  (SELECT COUNT(oc.OrderId) FROM [Order] oc WHERE oc.OrderId = o.OrderId AND c.OrderStatusId = 2) AS completedTrip,
  (SELECT COUNT(oc.OrderId) FROM [Order] oc WHERE oc.OrderId = o.OrderId AND oc.OrderStatusId = 3) AS CanceledTrip
FROM [Order] o
INNER JOIN VehicleCategory vc ON vc.VehicleCategoryId = o.VehicleCategoryId
WHERE CAST(o.OrderTime AS date) = '2017-03-13'
GROUP BY vc.VehicleCategoryName;

我想像这样形成我的数据:

VehicleCategoryName|Completed Trips | Canceled Trips
  Bugdet                100             20
  Premier               50              10
  Rocket                20              20

请帮助我对聚合做错了什么?

3 个答案:

答案 0 :(得分:1)

您不需要相关的子查询。您可以使用COUNT代替CASE

试试这个:

select vc.VehicleCategoryName,
    count(case when o.OrderStatusId = 2 then 1 end) as completedTrip,
    count(case when o.OrderStatusId = 3 then 1 end) as CanceledTrip
from [Order] o
inner join VehicleCategory vc on vc.VehicleCategoryId = o.VehicleCategoryId
where cast(o.OrderTime as date) = '2017-03-13'
group by vc.VehicleCategoryName

它使用以下情况:上述case语句仅在匹配条件下返回1,否则为null,count函数仅计算非空值。

答案 1 :(得分:0)

SELECT 
vc.VehicleCategoryName   ,
SUM(CASE WHEN o.OrderStatusId = 2 THEN 1 ELSE 0 END) as completedTrip , 
SUM(CASE WHEN o.OrderStatusId = 3 THEN 1 ELSE 0 END)  as CanceledTrip 

FROM [Order] o

inner join VehicleCategory vc
on vc.VehicleCategoryId = o.VehicleCategoryId
where cast(o.OrderTime as date) = '2017-03-13' 

group by vc.VehicleCategoryName 

答案 2 :(得分:0)

请试试这个,

SELECT vc.VehicleCategoryName,
  (SELECT COUNT(oc.OrderId) FROM [Order] oc WHERE oc.OrderId = o.OrderId AND c.OrderStatusId = 2) AS completedTrip,
  (SELECT COUNT(oc.OrderId) FROM [Order] oc WHERE oc.OrderId = o.OrderId AND oc.OrderStatusId = 3) AS CanceledTrip
FROM [Order] o
INNER JOIN VehicleCategory vc ON vc.VehicleCategoryId = o.VehicleCategoryId
WHERE CAST(o.OrderTime AS date) = '2017-03-13'
GROUP BY vc.VehicleCategoryName,o.OrderId