SQL Server:Sum和内部联接

时间:2014-03-11 11:02:51

标签: sql-server sum inner-join

我有两张桌子:

  • DepotSessionsID (int), Date (date), StartTime (int), EndTime (int), TruckID (int)
  • DepotSessionDetailsID (int), DepotSessionID (int), Status (varchar(20)), Duration (int)

我需要知道每辆卡车装载的次数(TotalLoadCount),加载的时间(TotalLoadTime)以及它在仓库中花费的时间(TotalDepotTime

给定DepotSessionRowsTruckID可以有多个Date。此外,给定DepotSessionDetails可能有多个DepotSessionID行。

一些示例数据:

DepotSessions

ID  TruckID  Date           StartTime   EndTime
-----------------------------------------------
1      1     '2013-04-01'      500        3000
2      1     '2013-04-01'    14000       25000

DepotSessionDetails

ID    DepotSessionID   Status    Duration
------------------------------------------
1          1           'Waiting'    40
2          1           'Loading'    25
3          1           'Waiting'    33
4          1           'Loading'    38
5          2           'Waiting'    100
6          2           'Loading'    167
7          2           'Waiting'    420
8          2           'Loading'    980

根据这个样本数据,我需要得到:

  • TotalDepotTime 13500(如25000 - 14000 + 3000 - 500)
  • TotalLoadTime 1210
  • TotalLoadCount 4

这就是我现在所拥有的:

SELECT 
    DS.Date, DS.TruckID, 
    MIN(DS.StartTime), MAX(DS.EndTime),
    SUM(DS.EndTime-DS.StartTime) TotalDepotTime,
    SUM(CASE WHEN DSD.Status = 'Loading' THEN DSD.Duration ELSE 0 END) TotalLoadTime,
    COUNT(CASE DSD.Status = 'Loading' THEN 1 ELSE 0 END) TotalLoadCount
FROM 
    DepotSessions DS
INNER JOIN 
    DepotSessionDetails DSD  on DS.ID = DSD.DepotSessionID
GROUP BY 
    Date, TruckID
  • TotalDepotTime 54000(不正确,应为13500)
  • TotalLoadTime 1210
  • TotalLoadCount 8(不正确,应为4)

2 个答案:

答案 0 :(得分:0)

  

除以该Date和TruckID的DepotSessions行数。

以上行不明确。 你可以这样试试,

select 
    *, TotalDepotTime * TotalLoadCount 
from 
    (SELECT 
         DS.Date, DS.TruckID, MIN(DS.StartTime), MAX(DS.EndTime),
         SUM(DS.EndTime-DS.StartTime) TotalDepotTime,
         SUM(CASE DSD.Status WHEN 'Loading' THEN DSD.Duration ELSE 0 END) TotalLoadTime,
         COUNT(CASE DSD.Status WHEN 'Loading' THEN 1 ELSE 0 END) TotalLoadCount
     FROM 
         DepotSessions DS
     INNER JOIN 
         DepotSessionDetails DSD ON DS.ID = DSD.DepotSessionID
     GROUP BY Date, TruckID) tbl

答案 1 :(得分:0)

试试这个:

SELECT DS.Date, DS.TruckID, 
       MIN(DS.StartTime), MAX(DS.EndTime),
       sum(distinct(DS.EndTime))-sum(distinct(DS.StartTime)) as TotalDepotTime,
       SUM( CASE DSD.Status WHEN 'Loading' THEN DSD.Duration ELSE 0 END) TotalLoadTime,
       SUM(CASE DSD.Status WHEN 'Loading' THEN 1 ELSE 0 END) TotalLoadCount
FROM DepotSessions DS
INNER JOIN DepotSessionDetails DSD  on DS.ID = DSD.DepotSessionID
GROUP BY TruckID, date;

fiddle