我有一个如下查询。表之间的关系是:
每辆卡车可能有多个司机。表列表将表Truck中的每一行与表Driver中的行连接起来。现在我想在一定条件下获得独特卡车的数量,以及在这种情况下独特卡车的总尺寸。
这就是我所拥有的:
SELECT t.Year AS [Year]
, t.Month AS [Month]
, t.Day AS [Day]
-- Count will not count NULL
, COUNT( DISTINCT (CASE WHEN (t.Sent = 1 AND r.Internal=1) THEN L.TruckId
ELSE NULL
END) ) AS [Count]
, SUM(CASE WHEN (t.Sent = 1 AND r.Internal = 1) THEN t.Size
END) AS [Size]
FROM Truck t
INNER JOIN List L ON t.Id = L.TruckId
INNER JOIN Driver r ON L.DriverId = r.Id
GROUP BY t.Year, t.Month, t.Day
我的问题是如何获得此SUM? 我不想写2个查询并加入。
由于
答案 0 :(得分:2)
您可以尝试如下查询:
; with cte as (
SELECT
DISTINCT
t.Year AS [Year]
, t.Month AS [Month]
, t.Day AS [Day]
, L.TruckId,
, t.Size
FROM Truck t
INNER JOIN List L ON t.Id = L.TruckId
INNER JOIN Driver r ON L.DriverId = r.Id
WHERE t.Sent = 1 AND r.Internal=1
)
select
Year
, Month
, Day
, count(TruckId) AS [Count]
, sum(Size) AS [Size]
from cte
group by Year, Month, Day