按行语法按行计算

时间:2017-01-23 19:28:34

标签: sql sql-server-2012 group-by sum

我使用以下查询

SELECT CONVERT(date,lot.Killdate) as KillDate
  ,lot.[LotNo]
  ,lot.[HotWeight]
  ,lot.[AverageYieldGrade]
  ,(lot.HeadShorn + lot.HeadUnshorn) as 'Total'
  ,(lot.HotWeight) / (lot.HeadShorn + lot.HeadUnshorn) as 'AvgWeight'  
  ,date.Date
  ,date.WeekOfYear
FROM [LambLot].[dbo].[LotHeader] lot, Master_Dim.dbo.DateDim date
WHERE CONVERT(date,lot.KillDate) = date.Date 
and lot.KillLocation = 1 
AND lot.HeadShorn > 0
AND lot.HeadUnshorn > 0
AND date.Year = 2016
group by lot.LotNo, lot.HeadShorn, lot.HeadUnshorn, lot.HotWeight lot.AverageYieldGrade, lot.KillDate, date.Date, date.WeekOfYear
order by date.WeekOfYear asc

这是输出的副本

    KillDate    LotNo   HotWeight   AverageYieldGrade   Total   AvgWeight           Date        WeekOfYear
1   2016-01-04  102     21603.5     2.28                348     62.0790229885057    2016-01-04  2
2   2016-01-04  103     2305.3      1.42                53      43.4962264150943    2016-01-04  2
3   2016-01-04  105     1159        0                   17      68.1764705882353    2016-01-04  2
4   2016-01-04  108     1493.6      0                   39      38.2974358974359    2016-01-04  2
5   2016-01-04  109     2982.8      0                   80      37.285              2016-01-04  2

我想要做的是将每一行加到每周。基本上给我52行输出,显示每列中每个值的总和。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

如果您只需要SUM WeekOfYear,则需要GROUP BY一年中的一周。你必须决定如何处理其他值,这是一种可能有意义的方法(通过一些预期的输出,你可以更容易地找出你真正想要的东西):

SELECT CONVERT(date, MAX(lot.Killdate)) as KillDate
  ,MAX(lot.[LotNo]) -- ?? Does this really belong in this query?
  ,SUM(lot.[HotWeight])
  ,AVG(lot.[AverageYieldGrade])
  ,(SUM(lot.HeadShorn) + SUM(lot.HeadUnshorn)) as 'Total'
  ,SUM(lot.HotWeight) / (SUM(lot.HeadShorn) + SUM(lot.HeadUnshorn)) as 'AvgWeight'  
  ,MAX(date.Date)
  ,date.WeekOfYear
FROM [LambLot].[dbo].[LotHeader] lot, Master_Dim.dbo.DateDim date
WHERE CONVERT(date,lot.KillDate) = date.Date 
and lot.KillLocation = 1 
AND lot.HeadShorn > 0
AND lot.HeadUnshorn > 0
AND date.Year = 2016
group by date.WeekOfYear
order by date.WeekOfYear asc

请记住:无论您GROUP BY列中的哪一列都将被考虑到如何计算出一个独特的群体。您在GROUP BY中没有但在输出中需要的任何内容只需要某种聚合函数(例如MINMAXAVG,{{1} },SUM等)。