2017-03-15 99 views
0

我想運行此查詢,但它給我錯誤。計算子查詢select語句中的聚合值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 

請幫忙什麼是錯的,我用骨料在做什麼?

+0

請不要使用JavaScript/HTML片段格式,除非它是Javascript或HTML或CSS – GrabNewTech

+0

哪個DBMS您使用的?在你的問題中有非標準的SQL –

回答

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 

它使用的事實,上述情況語句只會在匹配條件和空返回1,否則和count函數計算唯一的非空值。

+0

謝謝,但是如果我必須從另一個表像Like Fare table中獲取值來計算收益,該怎麼辦?對每個類別的總收入? –

+0

@naveedahmed - 你可以加入這個表。 – GurV

+0

可否請您編輯您的答案請我的表是票價有外鍵OrderId –

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 
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