如何在SQL中按年分组行的SUM

时间:2014-11-01 09:27:04

标签: sql sum aggregate-functions

SELECT          YEAR(OrderDate) 'Year', SUM(TotalDue)
FROM            Sales
GROUP BY        OrderDate
Order BY        OrderDate

如何将每年添加为一行? 我在上面编写了查询,但结果仍然将TotalDue by Year作为单独的行。 例如

enter image description here

5 个答案:

答案 0 :(得分:3)

GROUP BY语句中存在问题,因为它在选定的列上运行:

SELECT YEAR(OrderDate) theYear, SUM(Due) TotalDue
FROM Sales
GROUP BY theYear --Here you can either order by TotalDue or by theYear,
                 -- otherwise you will get the errors you mentioned

答案 1 :(得分:2)

你应该GROUP BY年,而不是OrderDate:

SELECT          YEAR(OrderDate), SUM(TotalDue)
FROM            Sales
GROUP BY        YEAR(OrderDate)
Order BY        OrderDate

答案 2 :(得分:1)

您应该按订单日期的年份进行分组,而不是OrderDate本身。

SELECT          YEAR(OrderDate) AS `Year`, SUM(TotalDue)
FROM            Sales
GROUP BY        YEAR(OrderDate)
Order BY        Year

答案 3 :(得分:0)

SELECT          YEAR(OrderDate) 'Year', SUM(TotalDue)
FROM            Sales
GROUP BY        YEAR(OrderDate)

答案 4 :(得分:0)

您需要重新分组结果

SELECT y, Sum(s) from 
  (
  SELECT          YEAR(OrderDate) as y , SUM(TotalDue) as s
    FROM            Sales
   GROUP BY        OrderDate
  )
group by y
Order BY y