SQL Query根据ID返回字段和

时间:2013-07-15 18:13:47

标签: c# asp.net sql-server-2008 gridview

顶部的图片是我在SQL表中的内容。

我有这个查询,它在底部gridview中给出了结果。该查询将在TransTypeDesc列中返回最大的EstimatedTransTime。如你所见,Car是第一季度最大的EstTransTime。

我唯一没有的是基于DisplayNum的TotalEstimatedTransTime。所以对于Q1我应该有31分钟。

  SELECT t1.DisplayNum, t1.TransTypeDesc, t1.SubQueueId, t1.EstimatedTransTime 
  FROM vwQueueData AS t1 
  LEFT OUTER JOIN vwQueueData AS t2 ON t1.DisplayNum = t2.DisplayNum AND t1.EstimatedTransTime < t2.EstimatedTransTime 
  WHERE (t2.DisplayNum IS NULL) AND (t1.Called IS NULL) AND (t1.SubQ = @SubQ) 

enter image description here

这里是SQL小提琴:http://sqlfiddle.com/#!3/a8983/1

1 个答案:

答案 0 :(得分:1)

您需要按照以下方式执行操作:

SELECT t1.DisplayNum, t1.TransTypeDesc, t1.SubQueueId, SUM(t1.EstimatedTransTime) 
FROM vwQueueData AS t1 
LEFT OUTER JOIN vwQueueData AS t2 
     ON t1.DisplayNum = t2.DisplayNum AND 
        t1.EstimatedTransTime < t2.EstimatedTransTime 
WHERE (t2.DisplayNum IS NULL) AND 
      (t1.Called IS NULL) AND (t1.SubQ = @SubQ)
GROUP BY t1.DisplayNum, t1.TransTypeDesc, t1.SubQueueId

基本上,将SUM函数添加到“EstimatedTransTime”列。 然后在DisplayNum列上执行group by以获得所需的输出。